如何通过js点击两张图片来回切换

JavaScript06

如何通过js点击两张图片来回切换,第1张

首先

if (oImg.src="img/1.png")

是赋值而不是判断相等, 判断相等请用==或者===

其次, 你的切换不应当依赖於从元素上读到的src, 而应当用变量维护当前的状态

示例

window.onload = function()

{

var

oImg = document.getElementById('img1'),

Picture = ['img/1.png','img/2.png'],

Index = 0

oImg.onclick = function()

{

++Index

Index < Picture.length || (Index = 0)

oImg.src = Picture[Index]

}

}

<!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=0i<pc.lengthi++){

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>