我使用responsiveslides库来获得响应式滚动图像。所以,我希望利用同一个库来获得响应式滚动文本,我编写了这个 JS 代码来计算字体高度,但它不起作用:
function responsiveText()
{
$('#footer').css('font-size', $('#footer').css('height'));
}
你可以在这里看到我失败的结果
我使用responsiveslides库来获得响应式滚动图像。所以,我希望利用同一个库来获得响应式滚动文本,我编写了这个 JS 代码来计算字体高度,但它不起作用:
function responsiveText()
{
$('#footer').css('font-size', $('#footer').css('height'));
}
你可以在这里看到我失败的结果
您可能需要考虑一些事情:
1)设置字体大小的代码只会被调用一次
2)您正在为孔容器设置字体大小,为什么不在css中进行呢?
<style>
.rslides li {
font-size: 30px;
}
</style>
3)但你希望它响应,对吧?然后,您必须考虑容器的字符数和宽度,将其乘以某个值,将该值设置为文本元素的字体大小,并对您拥有的每个文本元素执行此操作。或者不完全是,请查看以下代码:
所以是这样的:
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();
});
尝试用这个替换你的旧代码。(编辑)现在它应该工作得很好!测试了一段时间,尝试调整浏览器大小!剩下的唯一一件事(虽然不是关键)是确保有正确数量的行。祝你好运!