为什么我的文字没有响应?

时间:2014-03-20 23:33:10

标签: javascript responsive-design font-size responsive-slides

我使用responsiveslides库来获得响应式滚动图像。 所以,我希望利用相同的库来获取响应式滚动文本,我编写了这个JS代码来计算字体高度,但它不起作用:

function responsiveText()
{
    $('#footer').css('font-size', $('#footer').css('height'));
}

您可以在行动here

中看到失败的结果

1 个答案:

答案 0 :(得分:2)

有些事情你可能想要考虑:

1)设置字体大小的代码只会被调用一次

2)你正在设置洞穴容器的字体大小,为什么不在css中进行呢?

<style>
.rslides li {
    font-size: 30px;
}
</style>

3)但是你希望它能够做出回应,对吧?然后,您将必须考虑容器的字符数和宽度,将其与某些东西相乘,将该值设置为text-element的字体大小,并为您拥有的每个文本元素执行此操作。或者不完全相反,请看一下这段代码:

这样的事情:

 function responsiveText() {

    var ratio = 1/2; // character width/height
    var padding = 10;
    var width = $("#newsSlider").outerWidth()-padding*2;
    var height = $("#footer").outerHeight()-padding*2;

    $("#newsSlider").children().each(function () {
        var li = $(this); // one text element/list item
        var len = li.text().length; // number of characters
        var fw = width/len; // maximal character width = width/number of characters
        var fh = height; // maximal character height

        // We want fw/fh be so close to ratio as possible by changeing nr of lines
        var nrofl = 1;
        for (; nrofl<5; nrofl++) {
            var nnrofl = nrofl+1;
            var newRatio = (width/(len/nnrofl)) / (height/nnrofl);
            if (Math.abs(newRatio-ratio)<Math.abs(fw/fh-ratio)) {
                nrofl = nnrofl;
                fw = (width/(len/nrofl));
                fh = (height/nrofl);
            } else break;
        }

        // One thing's missing if you want a perfect result:
        // Go through the text and insert new lines to make sure
        // there will be nrofl lines. Not going to do it here though.

        // Fontsize is min of fw/ratio and fh
        var fs = Math.min(fw/ratio, fh);

        // For testing only
        //console.log(Math.round(fs), ratio, Math.round(fw), fh, width, height, nrofl, len);

        // Do not forget to round it up to integer value
        li.css('font-size', Math.round(fs)+'px');
    });

}

$(function() {

    // image slideshow
    $("#imageSlider").responsiveSlides({
        timeout: 20*1000,
    });

    // news slideshow
    $("#newsSlider").responsiveSlides({
        timeout: 5*1000,
    });


    // resposive news 
    $(window).resize(function(){
        responsiveText();   
    });
    responsiveText();

});

尝试用这个替换旧代码。 (编辑)现在它应该工作得很好!测试了一段时间,尝试调整浏览器的大小!只留下的东西(虽然不重要)是确保有适量的线条。祝你好运!