問題是這樣的:我有多個div層,每個div層有若干張圖片,我想實現圖片自動播放,但是用了setInterval()和onmouseover(),onmouseout()等函數,卻發現:
1每次鼠標要先移動到圖片上,再離開圖片,圖片才會自動播放,而不是我一進入網頁就自動播放每個div層的圖片
2每次最多有一個div層中的圖片會自動播放圖片,其余的不會自動播放圖片。
下面是我的代碼
你進頁面的時候又沒有執行播放,只有觸發時間了才播放。你的計時器是公用的,改為私有的
<script type="text/javascript">
function play_pic(object) {
var curIndex = 0;
var timeInterval = 1000;
var arr = new Array();
arr[0] = "https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017010912134691.jpg";
arr[1] = "https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017010912134660.jpg";
arr[2] = "https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017010912134608.jpg";
arr[3] = "4.jpg";
arr[4] = "5.jpg";
object.picTimer = setInterval(function () {
var obj = object;
if (curIndex == arr.length - 1) {
curIndex = 0;
}
else {
curIndex += 1;
}
obj.src = arr[curIndex];
}, timeInterval);
}
function stop_pic(object) {
clearInterval(object.picTimer);
}
window.onload = function () {
for (var i = 1; i < 4; i++) play_pic(document.getElementById('obj' + i));
}
</script>
</head>
<body>
<div id="div_1">
<img id="obj1" src="https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017010912134691.jpg" onmouseout="play_pic(this)" onmouseover="stop_pic(this)" />
</div>
<div id="div_2">
<img id="obj2" src="https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017010912134660.jpg" onmouseout="play_pic(this)" onmouseover="stop_pic(this)" />
</div>
<div id="div_3">
<img id="obj3" src="https://www.aspphp.online/bianchen/UploadFiles_4619/201701/2017010912134608.jpg" onmouseout="play_pic(this)" onmouseover="stop_pic(this)" />
</div>