gpt4 book ai didi

javascript - 我怎样才能对这段代码进行按键操作?

转载 作者:行者123 更新时间:2023-11-28 02:55:26 24 4
gpt4 key购买 nike

我是 JavaScript 和 jQuery 的新手,所以这是我的问题。我如何向这段代码添加一个简单的按键操作。就像我按向右箭头一样,转到下一张图片。如果我按左箭头,转到上一张图片。我自己查阅并尝试了一些东西,但我无法将任何东西集成到这个特定的代码中。

现在,我可以简单地使用另一个代码并使用灯箱画廊或其他东西,但我不想要那样,因为我已经在网站上找到了某个地方,我不能重新来过。

function showImage(smSrc, lgSrc) {
document.getElementById('largeImg').src = smSrc;
showLargeImagePanel();
unselectAll();
setTimeout(function() {
document.getElementById('largeImg').src = lgSrc;
}, 1)
}

function showLargeImagePanel() {
document.getElementById('largeImgPanel').style.display = 'block';


}

function unselectAll() {

if (document.selection)
document.selection.empty();
if (window.getSelection)
window.getSelection().removeAllRanges();
}
#largeImgPanel {
text-align: center;
display: none;
position: fixed;
z-index: 100;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(100, 100, 100, 0.8);
}
<img src="./images/t_p0001.jpg" style="cursor:pointer" onclick="showImage(this.src, './images/p0001.JPG');" />
<img src="./images/t_p0002.jpg" style="cursor:pointer" onclick="showImage(this.src, './images/p0002.JPG');" />
<img src="./images/t_p0003.jpg" style="cursor:pointer" onclick="showImage(this.src, './images/p0003.JPG');" />
<img src="./images/t_p0004.jpg" style="cursor:pointer" onclick="showImage(this.src, './images/p0004.JPG');" />
<div id="largeImgPanel" onclick="this.style.display='none'">
<img id="largeImg" style="height:100%; margin:0; padding:0;" />
</div>

最佳答案

要使用 JQuery 检测按键,您可以将函数绑定(bind)到 keydown 事件:

$(document).keydown(function(e) {
switch(e.which) {
case 37: // left
break;

case 38: // up
break;

case 39: // right
break;

case 40: // down
break;

default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});

(取自there)

要更改显示的 img,您可以按照以下方式做:

$("#largeImgPanel").html('<img src="./images/t_p0001.jpg"  style="cursor:pointer"');

然后您必须实现一个系统来了解正在显示的图像,并使用此信息来确定要显示的下一张图像。

编辑:根据要求,让它通过图像:

var imgs = ["./images/t_p0001.jpg", "./images/...", etc];

var currentImg = 0;

然后在 keydown 事件处理程序中,您将拥有:

case 37: // left
if (currentImg === 0) {
currentImg = imgs.length - 1;
}
else {
currentImg--;
}
break;
case 39: // right
if (currentImg === imgs.length - 1) {
currentImg = 0;
}
else {
currentImg++;
}
break;

然后您只需更新 img 标签的 src 属性(切换后):

if (e.which === 37 || e.which === 39) {
$("#largeImgPanel>img").attr("src", imgs[currentImg]);
}

关于javascript - 我怎样才能对这段代码进行按键操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37292392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com