列表项悬停切换图片时添加淡入淡出效果遇到问题如何解决
菜单悬停切换图片淡入淡出效果实现方案
原有代码问题说明
- 错误为
mouseover事件传入两个回调,该事件仅支持单个回调,双回调对应API为hover currentImage变量作用域错误,第二个回调中无法读取该值- 多层
parent()遍历DOM逻辑冗余易出错,且fadeOut回调中错误将src属性绑定到了img的父级元素 - 未做动画队列清空处理,快速切换菜单项时会出现动画堆叠混乱
正确实现代码
基础版本(悬停切换,移出恢复默认图)
// 提前缓存图片元素,避免每次事件触发重复查找 const $menuImg = $('#menu img'); // 存储初始默认图片路径,移出时恢复用 const defaultImg = $menuImg.attr('src'); $('#menu ul li a').hover(function() { // 获取当前菜单项对应图片路径 const targetImg = $(this).data('image'); // 清空已有动画队列,避免重叠 $menuImg.stop(true, true); // 先淡出,完成后替换路径再淡入 $menuImg.fadeOut(300, function() { $(this).attr('src', targetImg).fadeIn(300); }); }, function() { // 鼠标移出菜单项恢复默认图,不需要该功能可删除整个第二个回调 $menuImg.stop(true, true); $menuImg.fadeOut(300, function() { $(this).attr('src', defaultImg).fadeIn(300); }); });
简化版本(仅悬停切换,不恢复默认图)
const $menuImg = $('#menu img'); $('#menu ul li a').on('mouseenter', function() { const targetImg = $(this).data('image'); $menuImg.stop(true, true).fadeOut(300, function() { $(this).attr('src', targetImg).fadeIn(300); }); });
优化方案(避免图片加载空白)
可提前预加载所有菜单关联图片,避免首次切换时的加载延迟:
const imgUrls = $('#menu ul li a').map(function() { return $(this).data('image'); }).get(); imgUrls.forEach(url => { const img = new Image(); img.src = url; });
内容的提问来源于stack exchange,提问作者Majurac
相关产品推荐
相关产品推荐

