【问题标题】:jquery: bind multiple events, then unbind a couple of them? is this right?jquery:绑定多个事件,然后取消绑定其中几个?这是正确的吗?
【发布时间】:2010-09-20 09:31:13
【问题描述】:

绑定多个事件,然后解绑其中几个?是这样吗?

基本上,当您将鼠标悬停在元素上时,背景颜色会发生变化,然后当您将鼠标悬停在元素之外时会变回来,但是当您单击元素时,我想禁用悬停效果并将背景颜色更改为不同的颜色,所以用户知道他们点击了它。最好的方法是什么?谢谢!

$('.tellmereplies').bind({click: function() {
    $(this).animate({'backgroundColor':'#0099ff', 'color':'#fff'})
    $('.tellmereplies').unbind('mouseover','mouseout')
},mouseover: function() {
    $(this).animate({'backgroundColor':'#fbca54', 'color':'#fff'})
},mouseout: function() {
    $(this).animate({'backgroundColor':'#E4E4E4', 'color':'#c0c0c3'})
}
});

【问题讨论】:

  • 不要忘记.hover() 将简化绑定和解除绑定,因为它在一种方法中绑定了 mouseenter 和 mouseleave。
  • 如果你想切换mouseovermouseout,最好通过添加/删除class而不是取消绑定事件来切换它。

标签: javascript jquery bind unbind


【解决方案1】:

看看 jquery 的event namespacing。我认为这可能对你有用。

$("#div1").bind("event_name.namespace1");
$("#div1").bind("some_other_event.namespace1");
$("#div1").bind("event_name.namespace2");
$("div1").unbind(".namespace1");

【讨论】:

  • 在仔细研究之后,谢谢你。这正是帮助我在 jquery 中成长的原因。
【解决方案2】:

我想你正在寻找这个:

$('.tellmereplies').bind("click", function() {
    $(this).animate({'backgroundColor':'#0099ff', 'color':'#fff'})
    $(this).unbind('mouseover mouseout')
}).bind("mouseover", function() {
    $(this).animate({'backgroundColor':'#fbca54', 'color':'#fff'})
}).bind("mouseout", function() {
    $(this).animate({'backgroundColor':'#E4E4E4', 'color':'#c0c0c3'})
});

【讨论】:

  • 太棒了,我忘了提到,在我点击它并取消绑定 mouseover 和 mouseout 之后,如果用户再次点击它,它将重新打开并再次绑定它们,我尝试了一些事情但是没听懂,有什么办法吗?
【解决方案3】:

我主要在 CSS 中执行此操作。您可以使用 :hover 伪类为链接创建悬停效果

.tellmereplies:hover {
    color: #fff;
    background-color: #0099ff;
}

然后当用户点击链接时,为链接添加另一个类值并覆盖链接的悬停效果。

$('.tellmereplies').addClass('tellmereplies-clicked');

.tellmereplies-clicked {
    /* new colors */
}

.tellmereplies-clicked:hover {
    /* new colors */
}

【讨论】:

  • 虽然没有动画,但在我的代码中,我让它从一种颜色渐变到另一种颜色,它使它看起来更平滑和更好。
  • 哦,是的,我没有发现。您可以使用 CSS 过渡来实现该效果。目前只能在 Safari 和 Chrome 中使用,但有一点渐进增强。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 2011-01-19
相关资源
最近更新 更多