[英]Why while loop don't work?
I have a text in a single line (white-space: nowrap). 我在一行中有一个文本(空白:nowrap)。 I want to reduce the font size of this text if the width of it greater than the width of the parent-block.
如果文本的宽度大于父块的宽度,我想减小此字体的字体大小。
I use while loop. 我用while循环。 Why it doesn't work?
为什么不起作用? Width of "elemWidth" is not updated and loop and the cycle freeze?
宽度“ elemWidth”是否没有更新并且循环和循环冻结?
$('.slider__title-wrap').each(function(){
var width = $(this).width();
var fontSize = 50;
var elem = $(this).find('.slider__title');
var elemWidth = elem.width();
while(elemWidth >= width) {
fontSize = Math.floor(fontSize * 0.96);
elem.css({fontSize: fontSize+'px'});
};
})
var elemWidth = elem.width();
makes a copy of elem.width();
复制
elem.width();
You need to reevaluate elemWidth
into your loop : 您需要将
elemWidth
重新评估为循环:
$('.slider__title-wrap').each(function(){
var width = $(this).width();
var fontSize = 50;
var elem = $(this).find('.slider__title');
var elemWidth = elem.width();
while(elemWidth >= width) {
fontSize = Math.floor(fontSize * 0.96);
elem.css({fontSize: fontSize+'px'});
elemWidth = elem.width();
};
})
You don't seem to be changing either elemWidth
or width
inside the while
loop. 您似乎并没有在
while
循环中更改elemWidth
或width
。 So it will either never start, or never end. 因此,它将永远不会开始,也永远不会结束。 You need to update the values you're comparing before the loop ends:
您需要在循环结束之前更新要比较的值:
$('.slider__title-wrap').each(function(){
var width = $(this).width();
var fontSize = 50;
var elem = $(this).find('.slider__title');
var elemWidth = elem.width();
while(elemWidth >= width) {
fontSize = Math.floor(fontSize * 0.96);
elem.css({fontSize: fontSize+'px'});
width = $(this).width();
elemWidth = $(this).find('.slider__title').width();
};
});
Alternatively, eliminate the variables so you don't have to update anything: 或者,消除变量,这样就不必更新任何内容:
$('.slider__title-wrap').each(function(){
var fontSize = 50;
while($(this).width() >= $(this).find('.slider__title').width()) {
fontSize = Math.floor(fontSize * 0.96);
elem.css({fontSize: fontSize+'px'});
};
});
Incidentally, I'd use fontSize = fontSize-1;
顺便说一句,我将使用
fontSize = fontSize-1;
instead of multiplying by 0.96
, but it's probably a micro-optimization. 而不是乘以
0.96
,但这可能是微优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.