為什么沒效果
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
</head>
<body>
<!--頁面布局-->
? ? <!--圖片相關屬性設置-->
? ??
? ? <img style="position:absolute;left:0;top:0" src="http://img1.sycdn.imooc.com//53577ee900016c2102080260.jpg" id="myImage" ?/>
<!--滑動按鈕設置-->
<input type="button" id="btn" value="右移" style="position:absolute;left:10px;top:275px">
</div>
<script>
window.onload = function()
? ? {
var img = document.getElementById("myImage");
var btn = document.getElementById("btn");
? ? ? //綁定點擊事件
btn.onclick = function()
? ? ? ? {
imgSlide(); //點擊按鈕時執行滑動函數
}
var maxLeft=700;//向右滑動的極限值
//實現滑動函數
function imgSlide()
? ? ? ? { ? //每次點擊后向右滑動300px
? ? ? ? ? ? var endLeft=img.offsetLeft+300; ?
var slideTimer = setInterval(function()
? ? ? ? ? ? {
? ? ? ?//現在距離左邊的距離
if(imgLeft < endLeft)
? ? ? ? ? ? ? ? {
if(imgLeft < maxLeft)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? //將圖片的左偏移(left值)增加20px,注意單位
? ? ? ? ? ? ? ?img.style.left=imgLeft+20+'px';
}
? ? ? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? alert("最大右移量");
? ? ? ? ? ? ? ? ? ? ? ? clearInterval(slideTimer);
? ? ? ?//終止定時器函數
? ?}
}
? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? {
clearInterval(slideTimer);
}
},10);
}
}
</script>
</body>
</html>
2016-06-02
在定時器函數內沒有定義var imgLeft=img.offsetLeft;加上去就好了,