效果:mouseenter到li上出现背景图片,mouseleave后背景图片消失,click以后该背景图片被锁定
问题:简单的mouseenter,mouseleave和click事件不能达到预期的效果,因为当click事件结束后,同时也会触发mouseleave事件
解决方案:我们给每一个li一遍循环,给li动态添加flag属性,默认值为true,是这样的我们判断当flag为false给该li设置背景图片,为true给清空;所以当mouseenter的时候,给移入的li设置背景图片;当鼠标点击li的时候给li的flag设置为取反,而其余兄弟li的flag均赋予true的属性,给点击的li设置背景图片;最后通过判断flag来决定是否触发mouseleave事件,循环遍历li,如果li的flag为true的背景图片清空
代码示例,不完全针对这个,有html结构的差别
$(function () { $li = $(".gywm-content .content-main-left li"); $($li[0]).find("a") .css({ "background": "url('image/guanyuwomen_anniu_xuanzhogn.png')" , "color": " #ff2826" }); $li.each(function (index, ele) { ele.flag = true; }) $li.mouseenter(function () { $li.index = $(".gywm-content .content-main-left li").index($(this)); $(this).find("a").css({ "background": "url('image/guanyuwomen_anniu_xuanzhogn.png')" , "color": " #ff2826" }); }); $li.click(function () { $(this).siblings().each(function (index, ele) { ele.flag = true; }); this.flag = !this.flag; $li.index = $(".gywm-content .content-main-left li").index($(this)); $(".gywm-content .content-main-right li").removeClass("show"); $(".gywm-content .content-main-right li").eq($li.index).addClass("show"); $(this).find("a").css({ "background": "url('image/guanyuwomen_anniu_xuanzhogn.png')" , "color": " #ff2826" }); }) $li.mouseleave(function () { $li.each(function (index, ele) { if (ele.flag) { $(ele).find("a") .css({ "background": "" , "color": " #333333" }); } }) });})
转载于:https://www.cnblogs.com/QIQIZAIXIAN/p/6196716.html