You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

鼠标移入时如何从数组加载下一张顺序图片而非随机图片

实现方案

第一步:修正HTML重复ID问题

原生规范中id属性必须全局唯一,原代码重复使用id="image"会导致选择器异常,先统一调整为类名:

<section id="grid" class="desktop-image">        
    <div class="image-grid">
      <div class="image-item image01"></div>
      <div class="image-item image02"></div>
      <div class="image-item image03"></div>
      <div class="image-item image04"></div>
    </div> 
</section>

第二步:调整JS逻辑实现顺序轮播

新增索引变量记录当前图片位置,每次替换后索引自增,溢出数组长度时自动重置回0实现循环,同时简化重复的事件绑定代码:

var images = ['PK1.jpg','PK2.jpg','PK3.jpg','PK4.jpg','PK5.jpg','PK6.jpg','PK7.jpg','PK8.jpg','PK9.jpg','PK10.jpg'];
// 新增索引变量,记录下一张要使用的图片下标
var currentImgIndex = 0;

// 页面加载初始化背景图
$(".image-item").siblings().css({'background-image': 'url(assets/' + images[currentImgIndex] + ')'});
// 索引自增,准备下一次调用
currentImgIndex = (currentImgIndex + 1) % images.length;


// 批量绑定鼠标进入事件,无需逐个元素单独绑定
$('.image-item').mouseenter(function(){
    const $target = $(this);
    $target.addClass("hide");
    setTimeout(function() {
        // 按顺序取当前索引对应的图片
        $target.css({'background-image': 'url(assets/' + images[currentImgIndex] + ')'});
        // 索引自增,取模运算实现循环,遍历到最后一张后自动回到第一张
        currentImgIndex = (currentImgIndex + 1) % images.length;
    },1000);    
    setTimeout(function() {
        $target.removeClass('hide');
    },6000);
});

逻辑说明

  • 全局变量currentImgIndex统一记录图片数组的遍历进度
  • 取模运算% images.length保证索引永远在数组有效范围内,不会出现下标溢出报错
  • 批量绑定事件减少冗余代码,后续新增图片元素只需添加image-item类即可自动适配逻辑,无需额外编写事件代码

内容的提问来源于stack exchange,提问作者Serene

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:36:04