2013-09-29 54 views
0

我已經試過這樣:禁用/啓用的mouseenter和鼠標離開上點擊 - jQuery的

$('.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解決。

+3

'$(」 AAA ').off('mouseenter mouseleave')。on('mouseenter mouseleave');'你期望最後一部分做什麼? – Itay

+0

目前尚不清楚你想要達到的目標。爲了什麼目的?你的最後一行不會做你的想法;它會關閉綁定的事件處理程序,但「on」將不會執行任何操作,因爲您沒有指定回調。 – Utkanos

+0

^我該怎麼做? – weaponx

回答

3

你可以使用一些共享變量標誌時關閉功能:

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; 
}); 
+0

謝謝,它的工作原理。你能告訴我怎樣才能禁用該功能的一部分(問題的第二部分)。 – weaponx

+0

@weaponx答案更新 –

+0

嗨Shimon,我只有一個關於你的代碼的問題(如何「記住」所選擇的首選項/設置一個cookie) - http://stackoverflow.com/questions/19079658/jquery-toggle-function - 設置一個餅乾 – weaponx

0
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; 
    } 
}); 
1

喜歡的東西

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

+0

這也適用。謝謝。 – weaponx

相關問題