Javascript 按左右箭头以更改图像?

Javascript 按左右箭头以更改图像?,javascript,html,image,slideshow,arrow-keys,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="java

我有一个简单的幻灯片:

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

var-imgs=[“2.jpg”、“3.jpg”、“4.jpg”、“5.jpg”];
函数changeImage(){
document.getElementById(“imgClickAndChange”).src=imgs[0];
imgs.push(imgs.shift())
}

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

您可以检测JavaScript中的箭头键按下,然后将每个键附加到事件。显示了它是如何完成的,但本质上:

document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;

    if (e.keyCode == '37') {
        // left arrow
    }
    else if (e.keyCode == '39') {
        // right arrow
    }
}
查看实际操作中的答案(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>

变量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"];
函数更改图像(dir){
var img=document.getElementById(“imgClickAndChange”);
img.src=imgs[imgs.indexOf(img.src)+(dir | | 1)]| | imgs[dir?imgs.length-1:0];
}
document.onkeydown=函数(e){
e=e | | window.event;
如果(e.keyCode=='37'){
changeImage(-1)//左显示下一个图像
changeImage()
}
}
上述解决方案的功能:

  • 如果单击该图像,它将带您进入下一个图像,并在到达最后一个图像时重复该循环
  • 对于Left arrow(),其行为类似于单击

虽然您已经接受了答案,但我自己的解决方法是:

function imgCycle(e) {
    // obviously use your own images here:
    var imgs = ['nightlife', 'people', 'sports', 'cats'],
        // reference to the img element:
        imgElement = document.getElementById('imgClickAndChange'),
        // finding the string of the src after the last '/' character:
        curImg = imgElement.src.split('/').pop(),
        // finding that string from the array of images:
        curIndex = imgs.indexOf(curImg),
        // initialising the nextIndex variable:
        nextIndex;

    // if we have a keyCode (therefore we have a keydown or keyup event:
    if (e.keyCode) {
        // we do different things based on which key was pressed:
        switch (e.keyCode) {
            // keyCode 37 is the left arrow key:
            case 37:
                // if the current index is 0 (the first element in the array)
                // we next show the last image in the array, at position 'imgs.length - 1'
                // otherwise we show the image at the previous index:
                nextIndex = curIndex === 0 ? (imgs.length - 1) : curIndex - 1;
                break;
                // keyCode 39 is the right arrow key:
            case 39:
                // if curIndex + 1 is equal to the length of the images array,
                // we show the first element from the array, otherwise we use the next:
                nextIndex = curIndex + 1 === imgs.length ? 0 : curIndex + 1;
                break;
        }
        // if we don't have a keyCode, we check if the event-type (in lowercase)
        // is a mousedown:
    } else if (e.type.toLowerCase() === 'mousedown') {
        // I'm assuming you'd like to advance to the next image, rather
        // than regress to the previous (same check as above):
        nextIndex = curIndex + 1 === imgs.length ? 0 : curIndex + 1;
    }
    // setting the src of the image to the relevant URL + the string from the array
    // at the 'nextIndex':
    imgElement.src = 'http://lorempixel.com/200/200/' + imgs[nextIndex];
}

// binding a mousedown event-handler to the 'img' element:
document.getElementById('imgClickAndChange').addEventListener('mousedown', imgCycle);
// binding the keydown event-handler to the 'body' element:
document.body.addEventListener('keydown', imgCycle);

参考资料:


我已尝试将此项和另一项粘贴到“所以请回答”“但它不起作用。我还必须做什么才能使它工作?我应该在html上写些什么?我还必须将var imgs添加到此函数吗?耶!它起作用了。谢谢:)只有一件事,我希望左箭头返回并显示上一张图像,但它也显示下一张图像。我能做些什么来纠正这个问题?@Owly:左箭头没有显示上一个图像吗?我把所有的图像放在一起,用小提琴检查