【问题标题】:Jquery - bind/unbind hover script, small bit of code, not sure what to doJquery - 绑定/取消绑定悬停脚本,一小段代码,不知道该怎么做
【发布时间】:2011-04-14 23:34:38
【问题描述】:

我创建了 DIV.cb-toggle,当用户将鼠标悬停在此 div 上时,它会变为橙色,当他们将鼠标悬停在此 div 之外时,它会变为灰色,当用户单击此 div 时,它会变为灰色蓝色,告诉用户它已被选中。所以当它没有被选中时,它有 mouseenter mouseleave 动画,但是当它被选中时我想取消绑定 mouseenter mouseleave,我不希望悬停事件在它被选中时起作用,只有在它没有被选中时才起作用。做我想要完成的事情的最佳方法是什么?我想出了下面的代码,但我很确定这是一种可怕的方法,我不知道该怎么做。非常感谢您的帮助。

我的代码:

$('.cb-toggle').toggle(function() { 
      $(this).animate({"background":"blue", "color":"#fff;"});      
      $(".cb-toggle").unbind("click.myfadee");
   }, function() {
      $(this).animate({"background":"gray", "color":"#fff;"});
      $('.cb-toggle').trigger('mouseenter');
   });
});

我称之为绑定:

$(".cb-toggle").bind("click.myfadee", function(){
      $(".cb-toggle").mouseenter(function() {
      $(this).animate({"background":"orange", "color":"#fff;"});
   }).mouseleave(function() {
      $(this).animate({"background":"gray", "color":"#fff;"});
   });
});

我需要保留背景颜色动画,而且我没有使用 jquery UI,所以我无法在类之间制作动画。

【问题讨论】:

    标签: javascript jquery toggle bind unbind


    【解决方案1】:

    您知道,只需一点 CSS,就可以轻松实现。

    CSS

    .cb-toggle {
        background-color: gray;
        color: #fff;
    }
    .cb-toggle:hover {
        background-color: orange;
    }
    .cb-toggle.selected {
        background-color: blue;
    }
    

    HTML

    <a href="#" class="cb-toggle">Toggle This</a>​
    

    jQuery

    $('.cb-toggle').click(function() {
       $(this).toggleClass('selected');
    });​
    

    demo

    这只是一个例子,你可以扩展它来做你的动画。你可能也想要这个link

    With animation demo

    【讨论】:

    • 哇,伙计,你已经超越了。 jsfiddle 真的很摇滚。
    猜你喜欢
    • 1970-01-01
    • 2012-01-17
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多