javascript - 按左右箭头更改图像?

标签 javascript html image slideshow arrow-keys

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

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

当我这样点击时,我设法改变了图像:

<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>

问题是当我按下向右箭头(下一步)和向左箭头(返回)时,我还希望图像发生变化。 我该怎么做? 我已经尝试添加“onkeypress”事件,但似乎没有任何效果。我做错了什么。我是 javascript 的新手,所以如果你能帮助我,那就太好了。谢谢:)

最佳答案

查看实际答案 http://jsfiddle.net/7LhLsh7L/ ( fiddler 注意:因为它在按下箭头(左,右)键之前在编辑器本身中运行,所以您应该将焦点(只需单击结果区域)放在结果区域)

这是标记和脚本:

<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>

The features of above solution:

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

关于javascript - 按左右箭头更改图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26443828/

相关文章:

javascript - 如何从外部网站加载DIV?

javascript - 为什么 Array.prototype.slice(arguments, 2) 而不是初始化为空数组?

javascript - 使用 [filter, map, some, reduce etc] 从二维数组的子对象创建一维数组

javascript - 即使在casperjs中assertExist为true也找不到元素

android - 选择器的大小与 "normal"图像不同

javascript - 如何使用 Angular.js 或 Javascript 根据键值测量 Json 数组长度

html - 为什么散焦时底部会出现一些超标?

jquery - 更改事件链接的颜色并为其他链接保留不同的颜色

java - java 远处的 Sprite 变暗

html - Img 作为背景图像