我想要实现的是,当你将图像设置为 100% 时,它会很好地相应地缩放高度。我喜欢捕捉那个高度并对其进行处理。
<div id="view" style="width:950px;">
<img src="1.png" />
</div>
图像尺寸为 950x500 像素。但是,当我询问 View $( '#view' ).height()
的高度是多少时,它返回 16 像素。有谁知道为什么这样做?为什么它不返回 500 像素,因为这是图像的大小。
最佳答案
您需要先加载图像。试试这个:
<!DOCTYPE HTML>
<html>
<style>
div { width: 950px; }
img { width: 100%; }
</style>
<body>
<div>
<img src="1.png">
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$('img').load(function() {
var height = $('div').height();
console.log(height);
});
</script>
</body>
</html>
关于javascript - 为什么自动高度不适用于图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9355163/