2013-07-22 108 views
3

所以我有這個textarea在focus()上展開,並返回到blur()上的原始位置。
我遇到的問題是當點擊一個按鈕時停止模糊函數傳播(保持textarea爲焦點)。模糊功能事件停止傳播

$("#mytextarea").focus(function(){ 
    $(this).animate({"height": "50px",}, "fast"); 
}); 

$("#mytextarea").blur(function(e){ 
     if (e.target.id === 'button'){ 
     return false; 
     e.stopPropagation(); 
     e.cancelBubble = true; 
    } 
    else{ 
    $('#mytextarea').animate({"height": "20px",}, "fast"); 
    } 
}); 

我想出了一個解決辦法是更換:

$("#mytextarea").blur(function(e) 

$(document).click(function(e) 

但說實話,我不希望使用document.click,我的網頁已經是重在js上使用這種方法會讓它變慢。這裏有一個Fiddle

+0

三件事情。不執行'return'語句後的代碼。而且你不需要手動執行'e.cancelBubble = true;'; jQuery規範冒泡的預防 - 只需調用'e.stopPropagation()',你應該很好。在事件處理程序中使用'return false;'有效地執行和手動調用'e.preventDefault()'和'e.stopPropagation()'...一樣的功能,所以你不需要你有什麼 - 選擇使用什麼。 – Ian

+0

@Ian好吧,我只是試着用.stopPropagation(),但結果是一樣的,謝謝你 – Aaron

+1

對我來說有點晚了,但我認爲這可能是相關的:[委派焦點和模糊事件(在Quirksmode.org)](http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html)。 –

回答

0

了幾個小時,我得到它的工作,所以後,是不是很漂亮,但經過多次試驗似乎是好的。

var mousedownHappened = false; 
$("#mytextarea").focus(function(){ 
    $(this).animate({"height": "50px",}, "fast"); 
}); 

$('#mytextarea').blur(function() { 
    if(mousedownHappened) // cancel the blur event 
    { 

     mousedownHappened = false; 
    } 
    else // blur event is okay 
    { 
    $("#mytextarea").animate({"height": "20px",}, "fast"); 
    } 
}); 

$('#button').mousedown(function() { 
    mousedownHappened = true; 
}); 

這裏是一個工作Demo歸功於@Alex在這個問題B:how to prevent blur() running when clicking a link in jQuery?

0
$("#mytextarea").focus(function(){ 
    $(this).animate({"height": "50px",}, "fast"); 
}); 

$("#mytextarea").blur(function(e){ 
    if (e.target.id === 'button'){ 
     e.cancelBubble = true; 
     return false; // return needs to be last 
    } 
    // don't use else when you're returning because it's not needed   
    $('#mytextarea').animate({"height": "20px",}, "fast"); 
}); 
+0

目標'id'將始終是'mytextarea'而不是'button',所以這不起作用。 –

+0

@ matmar10抱歉,這不起作用。你可能想在我的q中查看演示 – Aaron

0

從選定的答案,我已經嘗試過使用,但我發現了一個問題。 這就是如果textarea被展開並且你點擊了兩次以上的按鈕 那麼動畫不起作用如果我沒有對焦/模糊兩次。所以我有另一種解決方案。

停止傳播在這種情況下最漂亮的解決方案

JSFiddle

$(document).ready(function() { 

    $("#mytextarea").focus(function (e) { 
     $(this).animate({ 
      "height": "50px", 
     }, "fast"); 
    }); 

    $('#button').click(function (e) { 
     e.stopPropagation(); 
    }); 

    $(document).click(function (e) { 
     $("#mytextarea").animate({ 
      "height": "20px", 
     }, "fast"); 
    }); 

});