按左右箭头更改图像?

Owl*_*wly 4 html javascript image slideshow arrow-keys

所以我有这个简单的幻灯片:

<div class="container">
    <div id="slideshow">
        <img alt="slideshow" src="1.jpg" id="imgClickAndChange" onclick="changeImage()" />
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

当我像这样单击时,我设法使图像发生了变化:

<script language="javascript">
    var imgs = ["2.jpg", "3.jpg", "4.jpg", "5.jpg"];

    function changeImage() {
        document.getElementById("imgClickAndChange").src = imgs[0];
        imgs.push(imgs.shift())
    }
</script>
Run Code Online (Sandbox Code Playgroud)

问题是当我按下右箭头(下一个)和左箭头(返回)时,我还希望图像发生变化。我怎样才能做到这一点?我试过添加一个“onkeypress”事件,但似乎没有任何效果。我做错了什么。我对 javascript 很陌生,所以如果你能帮助我,那就太好了。谢谢 :)

Kot*_*nga 5

在操作中查看答案http://jsfiddle.net/7LhLsh7L/ (提琴手注意:因为它在按箭头(左,右)键之前在编辑器中运行时,您应该将焦点(只需单击结果区域)放在结果区域)

这是标记和脚本:

<div class="container">
    <div id="slideshow">
        <img alt="slideshow" src="http://thumb7.shutterstock.com/photos/thumb_large/253822/156271139.jpg" id="imgClickAndChange" onclick="changeImage()" />
    </div>
</div>
<script>
    var imgs = ["http://thumb7.shutterstock.com/photos/thumb_large/253822/156271139.jpg", "http://thumb9.shutterstock.com/photos/thumb_large/554278/132632972.jpg", "http://thumb7.shutterstock.com/photos/thumb_large/101304/133879079.jpg", "http://thumb101.shutterstock.com/photos/thumb_large/422038/422038,1327874090,3.jpg", "http://thumb1.shutterstock.com/photos/thumb_large/975647/149914934.jpg", "http://thumb9.shutterstock.com/photos/thumb_large/195826/148988282.jpg"];

    function changeImage(dir) {
        var img = document.getElementById("imgClickAndChange");
        img.src = imgs[imgs.indexOf(img.src) + (dir || 1)] || imgs[dir ? imgs.length - 1 : 0];
    }

    document.onkeydown = function(e) {
        e = e || window.event;
        if (e.keyCode == '37') {
            changeImage(-1) //left <- show Prev image
        } else if (e.keyCode == '39') {
            // right -> show next image
            changeImage()
        }
    }
</script>
Run Code Online (Sandbox Code Playgroud)

上述解决方案的特点:

  • 如果您单击图像,它将带您到下一张图像,并在到达最后一张图像时重复循环。
  • 对于向左箭头(<-),它加载前一个图像,并在到达第一个图像时以相反的方向循环重复。
  • 右箭头 (->) 行为类似于单击。