从 Jquery 1.8 开始,获取元素的 height() 时发生了变化。我有一个 CSS div 高度设置为自动,里面的图像通过使用 % 和 auto 来指示 div 的高度和宽度),当窗口加载时我使用 Jquery 来获取元素的高度并在它旁边制作另一个 div同样的高度。对此进行研究后,我注意到它在 CSS 设置图像设置的新高度之前返回高度。 1.7 允许这样做,但 1.8 及更高版本不允许。是一种解决方法。 这是CSS
#element1{ width:80%; height:auto;}
#element1 img{width:100%; height:auto};//this allows the image to resize with the page responsively.
jQuery...
$(window).ready(
function(){
var x = $("#element").height();
alert(x); // this would return what the height was dynamically set as by the css in 1.7, but 1.8 returns a small number that i am pretty certain is just the padding added to 0px
});
希望这是有道理的,并且有人可以解决这个问题。 谢谢
最佳答案
而不是监听 $(window).load()
,这可能会在成功加载所有资源之前停止适当的高度分配,您可以在每个 <img>
上收听成功加载实例并触发适当的高度计算。
然而,由于在您的问题中您只有一个元素与动态设置高度有关,因此我减少了我的脚本而无需遍历所有 <img>
页面上的实例。假设您有以下标记:
<div id="element1">
<img ... />
</div>
您可以创建一个新图像,检查它是否已加载,然后指示 jQuery 运行高度计算并在完成后设置新高度:
$(function() {
var $img = $('<img />', {
'src': $('#element1 img').attr('src')
});
$img.load(function() {
$('#element2').css('height', $('#element1').height());
});
});
关于javascript - jquery 1.8 及更高版本,将一个 div 的高度设置为与另一个 div 相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26790396/