【问题标题】:disable / enable mouseenter and mouseleave on click - jquery [closed]单击时禁用/启用 mouseenter 和 mouseleave - jquery [关闭]
【发布时间】:2013-09-29 11:36:59
【问题描述】:

我试过了:

$('.aaa').mouseenter(function () {
    $(this).css('background', '#aaaaaa');
    $(this).css('border', 'solid 1px red');
});
$('.aaa').mouseleave(function () {
    $(this).css('background','blue');
});
$('#tog').click(function () {
      $('.aaa').off('mouseenter mouseleave').on('mouseenter mouseleave');
});

http://jsfiddle.net/z8KuE/13/

它不起作用 - 只是关闭事件/功能。

另外,如何只切换功能的一部分——例如只是$(this).css('background', '#aaaaaa');——而不是切换整个功能?

编辑: solution 1solution 2。由 Shimon Rachlenko 解决。

【问题讨论】:

  • $('.aaa').off('mouseenter mouseleave').on('mouseenter mouseleave'); 你希望最后一部分做什么?
  • 不清楚您要达到的目标。达到什么目的?你的最后一行不会像你想的那样做;它将关闭绑定的事件处理程序,但 on 不会做任何事情,因为您没有指定回调。

标签: javascript function toggle jquery


【解决方案1】:

您可以使用一些共享变量来标记何时关闭该功能:

var flag = true;
$('.aaa').mouseenter(function () {
    if(flag) { // enable this functionality only when flag is set
        $(this).css('background', '#aaaaaa');
    }
    $(this).css('border', 'solid 1px red');
});
$('.aaa').mouseleave(function () {
    if(!flag) return;
    $(this).css('background','blue');
});
$('#tog').click(function () {
    flag = !flag;
});

【讨论】:

  • 谢谢,它有效。你能告诉我如何只禁用功能的一部分(问题的第二部分)。
  • @weaponx 回答已更新
  • 嘿 Shimon,关于您的代码,我只有一个问题(如何“记住”选择的偏好/设置 cookie)-stackoverflow.com/questions/19079658/…
【解决方案2】:

类似

function mouseenterbk() {
    $(this).css('border', 'solid 1px red');
}

function mouseenter() {
    $(this).css('background', '#aaaaaa');
}

function mouseleave() {
    $(this).css('background', 'blue');
}

$('.aaa').on('mouseenter.bk', mouseenterbk).mouseenter(mouseenter).mouseleave(mouseleave);

//this is a very dump implementation of the click toggle
var flag;
$('#tog').click(function () {
    if (flag) {
        $('.aaa').on('mouseenter.bk', mouseenterbk);
        flag = false;
    } else {
        $('.aaa').off('mouseenter.bk');
        flag = true;
    }
});

演示:Fiddle

【讨论】:

  • 这也有效。谢谢。
【解决方案3】:
 var toggle = false;

 $('#tog').click(function () {
  if(toggle == false){
    $('.aaa').mouseenter(function () {
        $(this).css('background', '#aaaaaa');
        $(this).css('border', 'solid 1px red');
    });
    $('.aaa').mouseleave(function () {
         $(this).css('background','blue');
    });
    toggle = true;
  }
  else{
        $('.aaa').off('mouseenter mouseleave');
        toggle = false;
  }
 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多