能够启用滚动条,现在问题是无法正常循环切换图片
时间: 2024-04-17 15:27:01 浏览: 14
非常抱歉之前的回答仍然有误。根据您的描述,问题在于无法实现循环切换图片。
为了解决这个问题,您可以尝试使用以下修改后的代码:
```javascript
// 添加键盘事件
document.onkeydown = function (e) {
// 检查是否显示悬浮窗
if (isPopupVisible) {
// 获取所有具有相同类名的图片元素
var imgs = document.querySelectorAll('.preview-image');
var currentIndex = Array.from(imgs).indexOf(img); // 获取当前图片在数组中的索引
// 禁用页面滚动条
document.body.style.overflow = "hidden";
switch (e.keyCode) {
case 37: // 左箭头键
currentIndex = (currentIndex - 1 + imgs.length) % imgs.length;
break;
case 39: // 右箭头键
currentIndex = (currentIndex + 1) % imgs.length;
break;
}
// 更新图片源
img.src = imgs[currentIndex].src;
}
// 启用页面滚动条
document.body.style.overflow = "auto";
};
```
在上述代码中,我们将启用页面滚动条的代码移至了键盘事件处理程序的末尾,这样每次按下方向键后都会将页面滚动条重新启用。同时,确保在更新`currentIndex`之前,先进行了循环计算以确保索引值在合法范围内。
希望这次能够解决您的问题!如果还有其他疑问,请随时提问。