首页 > 解决方案 > 按下右箭头时转到下一个图像元素

问题描述

所以如果我在 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++}`
      }
    }

但没有用

标签: javascripthtml

解决方案


您不应该更改 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>


推荐阅读