javascript - 按下右箭头时转到下一个图像元素
问题描述
所以如果我在 HTML index.html 上有这样的元素
<div><img id="2" src="1.jpg"><img id="2" src="2.jpg"></div>
像这样由js创建的
index.js
let image = document.createElement("img")
image.src = img.image
image.style.width = "725"
image.style.height = "1024"
image.setAttribute("id",img.index)
如果按下右箭头,我该怎么做才能进入下一个图像索引的顶部
我试过这个
image.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == '37') {
document.location.href = `#${img.index--}`
} else if (e.keyCode == '39') {
document.location.href = `#${img.index++}`
}
}
但没有用
解决方案
您不应该更改 document.location,脚本将不得不重新运行,因为页面已重新加载。取而代之的是scrollIntoview:
也不需要索引,你可以从内容计算索引
const imageArr = [
"https://via.placeholder.com/725x1024/000000/FFFFFF/?text=image1",
"https://via.placeholder.com/725x1024/FF0000/0000FF/?text=image2",
"https://via.placeholder.com/725x1024/FFAAFF/00AA00/?text=image3"
]
const container = document.getElementById("imageContainer");
container.innerHTML = imageArr.map(img => `<img src="${img}" />`)
const images = container.querySelectorAll("img");
let current = 0;
const max = imageArr.length
window.addEventListener("keydown", function(event) {
if (event.defaultPrevented) {
return; // Do nothing if event already handled
}
const key = event.code;
if (key === "ArrowLeft") current--;
else if (key === "ArrowRight") current++
// wrap
if (current < 0) current = max; // change to current=0 if no wrap
else if (current >= max) current = 0; // change to current = max if no wrap
images[current].scrollIntoView()
})
<div id="imageContainer"></div>
推荐阅读
- python - 有效地将列表列表附加到 pandas DataFrame
- php - 有没有更好的方法将嵌套 for 循环中的变量从控制器传递到视图?
- python - 如何删除所有列但不首先删除以模式开头的列?
- java - 复合未来未完成
- scala - 错误:找不到类型 org.apache.spark.sql.Dataset[(String, Long)] 的编码器
- linq-to-sql - 如果包含组连接,则 SQL 语句中将忽略 Linq Take
- python - 内部类定义不断要求自我论证
- node.js - Cypress 在 Ubuntu 上永远无法通过加载屏幕
- mixed - 混合内容:“”处的页面是通过 HTTPS 加载的,但请求了不安全的 XMLHttpRequest 端点“”。此请求已被阻止
- javascript - 使用 Exclude 和 | 时鉴别器未按预期工作