为了账号安全,请及时绑定邮箱和手机立即绑定

为什么这个代码去掉window.onload = function(){}就会出现错误呢?

为什么这个代码去掉window.onload = function(){}就会出现错误呢?

<style type="text/css">

#contain{

height:477px;

position:relative;

margin:0 auto;

overflow: hidden;

border-right: 1px solid #ccc;

border-bottom: 1px solid #ccc;

}

img{

display: block;

position: absolute;

left:0;

border-left: 1px solid #ccc;

}

</style>

</head>

<body>

<div id='contain'>

<img src="img/door1.png" />

<img src="img/door2.png" />

<img src="img/door3.png" />

<img src="img/door4.png" />

</div>

<script type="text/javascript">

// window.onload = function(){

var imgs = document.getElementsByTagName('img');

var box = document.getElementById('contain');

var exploseWidth = 160;

var imgWidth = imgs[0].offsetWidth;

var boxWidth = imgWidth + (imgs.length-1) * exploseWidth;

box.style.width = boxWidth + 'px';

function startMove(){

for(var i=1;i<imgs.length;i++){

imgs[i].style.left = imgWidth + exploseWidth * (i-1) + 'px';

}

}

startMove();

// }

</script>

</body>


正在回答

4 回答

原来是符号问题

yfmttodehjif

0 回复 有任何疑惑可以回复我~

你试试将window.onload=function(){}去掉之后在控制台打印console.log(imgWidth);是不是输出为0?这个意思就是不加的话,js优先于图片加载

0 回复 有任何疑惑可以回复我~

window.onload是指基于页面加载完成后才做的事情,若页面没加载完,滑动效果也就无法实现。

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

为什么这个代码去掉window.onload = function(){}就会出现错误呢?

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信