jquery:在元素的鼠标悬停/鼠标移出时切换类,但如果单击元素内部则保留类?
我怀疑我在这件事上太聪明了!
我正在开发一个 jQuery 插件函数,当您将鼠标悬停在元素上/移出时,该函数将在元素上打开/关闭类,但如果您在悬停之前单击元素内部,则不会删除该类,并且如果元素在悬停之前已经具有该类。
我尝试提出以下
$.fn.showHover = function(settings) {
this.bind('mouseover', function hoverIn(){
if ($(this).hasClass('active') == false) {
$(this).addClass('active');
$(this).bind('click', function getFocus(){
$(this).unbind('mouseout', hoverOut);
})
$(this).bind('mouseout', function hoverOut(){
$(this).removeClass("active");
$(this).unbind('click', getFocus);
})
}
})
return this;
};
想法: ...如果您在单击之前将鼠标悬停在外面,则删除该类并取消绑定单击 - 如果您在悬停之前单击,则取消绑定 mouseout 并且该类永远不会获得已删除。
显然(因为我在这里寻求帮助!)它不起作用 - 无论我在悬停之前是否在元素内部单击,该类都会被删除。
有人能指出它失败的原因,并可能提出更好的解决方法吗?谢谢!
suspect I'm trying to be too clever for my own good with this one!
I'm working on a jQuery plugin function that will toggle a class on/off on an element when you hover in/out, but doesn't remove the class if you click inside the element before hovering out and doesn't toggle if the element already has that class before hovering in.
I tried coming up with the following:
$.fn.showHover = function(settings) {
this.bind('mouseover', function hoverIn(){
if ($(this).hasClass('active') == false) {
$(this).addClass('active');
$(this).bind('click', function getFocus(){
$(this).unbind('mouseout', hoverOut);
})
$(this).bind('mouseout', function hoverOut(){
$(this).removeClass("active");
$(this).unbind('click', getFocus);
})
}
})
return this;
};
...the idea if you hover out before clicking, remove the class and unbind click - if you click before hovering out, unbind mouseout and the class never gets removed.
Obviously (since I'm asking here for help!) it doesn't work - the class gets removed whether I click inside the element before hovering out or not.
Can anybody point out why it's failing, and possibly suggest a better way around it? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果通过 CSS 更改元素的外观是您的目标,一个简单的解决方案是添加另一个具有不同名称的选择器。
然后绑定悬停/取消悬停事件以添加/删除“active_hover”类,并绑定单击事件以添加“active_click”类。
If changing the appearance of the element is your goal through CSS, one easy solution is to simply add another selector, with a different name.
Then bind the hover/unhover event to add/remove the "active_hover" class, and the click event to add the "active_click" class.
你可以这样做,
所以当你悬停时,会设置一个内联CSS,如果你将鼠标悬停在div之外,jquery设置的内联样式将被删除..如果你点击它。其上设置了硬等级,因此不会相互干扰。
You could do this
So when you hover, a inline css is set and if you hover out of the div the inline style set by the jquery is removed.. And if you click on it. a hard class is set on it so it does not interfere with eachother.