所以我有这个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 :(得分:1)
所以经过几个小时后我才开始工作,并不漂亮,但经过多次测试似乎没问题。
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;
});
在此问题中,以下是@Alex b的Demo有效信用:how to prevent blur() running when clicking a link in jQuery?
答案 1 :(得分: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" );
});
答案 2 :(得分: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");
});
});
答案 3 :(得分:0)
您可以使用“ focusout”事件来代替使用“ blur”事件。它类似于模糊,但在DOM树中冒泡。 参见此stackoverflow answer。