我正在尝试以下代码,但它不起作用。从逻辑上讲应该没问题,但是谁能告诉我我在这里缺少什么?目标是 (h1) 标签的字体大小应根据其父标签的高度自动调整。
HTML
<div class="product-title">
<h1>Some Title which should not cross parent height and adjust font-size dynamically</h1>
</div>
CSS
.product-title{
height: 200px;
width: 200px;
}
JS
function adjustFontSize() {
$('#h1').each(function() {
var child = $(this);
var parent = child.parent();
child.css('font-size', '18'); //set max default font size
while (child.height() > parent.height() && parseInt(child.css('font-size')) > 9) { //check div height condition
child.css('font-size', (parseInt(child.css('font-size')) - 1) + "px"); //decrease font size accordingly
}
});
}
最佳答案
好的,到此为止。这应该是你要找的。让我知道它是否不适合你!
$(window).load(function() {
function adjustFontSize() {
$('.product-title h1').each(function() {
var child = $(this);
var parent = child.parent();
var fontSize = 3;
child.css("font-size", fontSize + "em");
while (child.height() > parent.height() && fontSize > .75) { //check div height condition
fontSize -= .05;
child.css('font-size', fontSize + "em"); //decrease font size accordingly
}
});
}
adjustFontSize();
});
关于jquery - 子元素字体大小根据父元素的高度动态调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36223359/