我是初学者,我正在尝试显示图像的宽度。当我第一次加载它给出正确的宽度,如果我重新加载它显示宽度为0.再次当我尝试加载铬选项“空缓存和硬重新加载”时,它显示正确的宽度。请揭开神秘面纱,我无法理解。
<html>
<head>
<style type="text/css">
#latest_albums{
overflow: hidden;
margin: 1em 1em;
background-color: #009999;
}
.album li{
list-style-type: none;
float: left;
overflow: hidden;
margin: 2px 2px 0px 0px;
position: relative;
}
</style>
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
</head>
<body>
<div id="latest_albums">
<div class="album">
<div class="set1">
<li> <img src="albums/image1.jpg"> </li>
<li> <img src="albums/image2.jpg"> </li>
<li> <img src="albums/image3.jpg"> </li>
<li> <img src="albums/image4.jpg"> </li>
<li> <img src="albums/image5.jpg"> </li>
<li> <img src="albums/image6.jpg"> </li>
</div>
<div class="set2">
<li> <img src="albums/image1.jpg"> </li>
<li> <img src="albums/image2.jpg"> </li>
<li> <img src="albums/image3.jpg"> </li>
<li> <img src="albums/image4.jpg"> </li>
<li> <img src="albums/image5.jpg"> </li>
<li> <img src="albums/image6.jpg"> </li>
</div>
</div>
</div>
<script type="text/javascript">
var i=0,w = -150,SCROOL_WIDTH,WIN_WIDTH,IMG_MARGIN,IMG_WIDTH=10,TOT_ALBUMS,ALBUM_WIDTH;
IMG_WIDTH = $("div.album li").eq(0).width();
console.log(IMG_WIDTH);
</script>
</body>
</html>
谢谢,
拉维
答案 0 :(得分:0)
您应该等到图像加载后才能获得它的宽度(否则它将返回0,因为它不知道它的大小)。试试这个:
$("div.album li:first img").load(function(){
IMG_WIDTH = $("div.album li").eq(0).width();
console.log(IMG_WIDTH);
});
答案 1 :(得分:0)
试试这样:
<script type="text/javascript">
$(document).ready(function() {
var i=0,w = -150,SCROOL_WIDTH,WIN_WIDTH,IMG_MARGIN,IMG_WIDTH=10,TOT_ALBUMS,ALBUM_WIDTH;
IMG_WIDTH = $("div.album li").eq(0).width();
console.log(IMG_WIDTH);
});
</script>
还会在加载图像时执行事件处理程序image.onload
。有时甚至不会触发image.onload
,因此您可以使用计时器检查图像宽度何时超过0.检查:jQuery or Javascript check if image loaded