JavaScript中换图片的问题

发布网友

我来回答

1个回答

热心网友

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>RunJS</title>
<style>
#num span.active { background-color: red; } 
#num span.wait { background-color: black; }
</style>
<script type="text/javascript">

    var imgArray = ['img/game1.png', 'img/game2.png', 'img/game3.png', 'img/game4.png'];
    var spanArray = document.getElementsByTagName('span');
    var img;
    var index = 0;
    var t;

    function init() {
        img = document.getElementById("img");
        img.src = "img/game1.png";
        startRotate();
    }

    function showImg() {
        img.src = imgArray[index];
        for (var i = 0; i < spanArray.length; i++) {
            spanArray[i].className = "wait";
        }
        spanArray[index].className = "active";
    }
 
    function rotate() {
        index++;
        if (index >= imgArray.length) {
            index = 0;
        }
        showImg();
    }

    function startRotate() {
        t = setInterval(rotate, 2000);
    }

    function pauseRotate(obj) {
        clearInterval(t);
// 估计是innerText不兼容导致出错
        index = getIndex(obj);
        showImg();
    };
//获取在父元素中的索引即可
var getIndex = function(obj){
var par = obj.parentElement;
var pc = par.children;
for(var i=0;i<pc.length;i++){
if(pc[i]==obj){
return i;
}
}
return -1;
};
</script>
</head>
<body onload="init()"> 
<img id="img" />
<div id="num">
<span class="active" 
onmouseover="pauseRotate(this)" onmouseout="startRotate()">1</span>
<span class="wait" onmouseover="pauseRotate(this)" onmouseout="startRotate()">2</span>
<span class="wait" onmouseover="pauseRotate(this)" onmouseout="startRotate()">3</span>
 <span
    class="wait" onmouseover="pauseRotate(this)" onmouseout="startRotate()">4</span>
</div>
</body>
</html>

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com