所以我有一个文本区域,它在focus()上展开,并返回到blur()上的原始位置
我遇到的问题是在单击按钮时停止模糊函数传播(保持文本区域聚焦)。
$("#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
所以几个小时后我就开始工作了,这并不漂亮,但经过多次测试后似乎还可以。
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在这个问题上的一个演示学分:如何防止点击jQuery中的链接时运行blur()?
$("#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" );
});
根据所选答案,我尝试过使用它,但发现了一个问题。也就是说,如果文本区域被展开,并且您点击按钮两次以上如果我两次都没有聚焦/模糊,那么动画就不起作用。所以我有了另一个解决方案。
在这种情况下,停止传播是最漂亮的解决方案
参见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");
});
});
您可以使用"focusout"事件而不是使用"blur"事件。它类似于blur,但在DOM树中冒泡。看看这个stackoverflow的答案。