如何在jQuery中实现点击事件激活时禁用hover效果?
解决点击图标后hover效果不再触发的问题
核心思路
要实现点击tag-icon-arrow图标后hover效果不再生效,核心是让hover事件的回调逻辑在元素处于"点击激活"状态时跳过执行,或者直接在点击后解绑hover事件。下面提供两种可行的优化方案:
方案一:在hover回调中判断激活状态,跳过处理
修改highlight函数,当触发源是hover(即clicked参数未传入或为false)时,先检查元素是否带有active类,若已激活则直接返回,不执行hover相关的高亮逻辑:
highlight: function (e, canHighlight, clicked) { let me = this , $target = $(e.currentTarget) , _id = $target.attr('data-id') , tagid = $target.attr("data-tagid") , tbId = me.isZone ? $target.attr("data-M") : ""; // 新增:hover触发且元素已激活时,直接返回 if (!clicked && $target.hasClass("active")) { return; } if (canHighlight) { clicked ? $target.addClass("active") : $target.removeClass("active"); if (tbId === undefined) tbId = ""; let objData = [{"_id": _id, "tagid": tagid,}]; Common.Gateway.onEventsToXYZ({ "event": "xyz", "fids": me.isZone ? [] : objData, "rids": me.isZone ? objData : [] }); me.api.xyz(tagid); } else { if ($target.is(".active")) return; Common.Gateway.onEventsToXYZ({ "event": "xyz" }); me.api.xyz(null); $target.removeClass("active"); } },
同时,合并bindViewEvents中重复的click事件绑定,避免多次绑定同一事件:
bindViewEvents: function () { let me = this , window = this.$window , $tagArrow = window.find(".tag-icon-arrow"); // 合并click事件,避免重复绑定 $tagArrow.off().on('click', function (e) { me.highlight(e, true, true); me.selectRole(e); }); $tagArrow.hover( function (e) {me.highlight(e, true);}, function (e) {me.highlight(e, false);} ); },
方案二:点击后直接解绑hover事件
如果需求是点击后永久禁用hover效果(不需要恢复),可以在click事件触发后,直接解绑hover事件:
bindViewEvents: function () { let me = this , window = this.$window , $tagArrow = window.find(".tag-icon-arrow"); // 定义hover回调函数,方便后续解绑 const hoverIn = function (e) {me.highlight(e, true);}; const hoverOut = function (e) {me.highlight(e, false);}; $tagArrow.off().on('click', function (e) { me.highlight(e, true, true); me.selectRole(e); // 点击后解绑hover事件 $(this).off('mouseenter mouseleave', hoverIn, hoverOut); }); $tagArrow.hover(hoverIn, hoverOut); },
这种方式更直接,一旦点击就彻底移除hover事件的监听,适合不需要恢复hover效果的场景。
内容的提问来源于stack exchange,提问作者SDP
相关产品推荐
相关产品推荐

