2016-11-07 113 views
1

確定我的代碼看起來某事像這樣:jQuery的切換

<div id="left" style="float:left; width:100px; margin-right:10px;"> 
<input id="first" value="something"> 
</div> 
<div id="right" style="margin-left:20px; float:left; width:200px;"> 
<input id="second" value="something"> 
<input id="third" value="something"> 
<input id="fourth" value="something"> 
</div> 

的jQuery:

$(function() { 

$("#right").focusin(function() { 
     $("#left").animate({ 
     width: "200px" 
     }, 500); 
     $("#right").animate({ 
     width: "100px" 
     }, 500); 
}); 
$("#right").focusout(function() { 
     $("#left").animate({ 
     width: "100px" 
     }, 500); 
     $("#right").animate({ 
     width: "200px" 
     }, 500); 
}); 

}) 

但是當右格輸入之間的IM點擊它調用的focusIn /出,如何防止這個?

DEMO: https://jsfiddle.net/swfzmdfd/

回答

0

您可以使用一個計時器,而不是做動畫,如果activeElement是其他輸入一個

$(function() { 
 
    $("#right").focusin(function(e) { 
 
     $("#left").stop(true,true).animate({ 
 
      width: "200px" 
 
     }, 500); 
 
     $("#right").stop(true,true).animate({ 
 
      width: "100px" 
 
     }, 500); 
 
    }); 
 
    $("#right").focusout(function() { 
 
    \t setTimeout(function() { 
 
     \t if (!($(document.activeElement).closest('#right').length && 
 
        $(document.activeElement).is('input'))) { 
 
       $("#left").animate({ 
 
        width: "100px" 
 
       }, 500); 
 
       $("#right").animate({ 
 
        width: "200px" 
 
       }, 500); 
 
      } 
 
     },100); 
 
    }); 
 

 
})
input { 
 
    width: 100px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="left" style="float:left; width:100px; margin-right:10px;"> 
 
    <input id="first" value="something"> 
 
</div> 
 
<div id="right" style="margin-left:20px; float:left; width:200px;"> 
 
    <input id="second" value="something"> 
 
    <input id="third" value="something"> 
 
    <input id="fourth" value="something"> 
 
</div>

+0

謝謝!這接近完美,虐待添加一些東西,這將是現在最好的解決方案現在 –

+0

唯一的錯誤是,當從這個div輸入聚焦=所有好的 但從任何其他元素,如空間在該div那麼它不起作用 ,因爲我做了正確的點擊事件 ,然後作爲您的演示集中注意 我認爲我需要改變它focusin而不是點擊並忘記這一點,因爲它的工作和工作 –

0
當你點擊

可以說,第三ID點擊第二個ID後,基本上這兩個事件被觸發,在的focusIn和事件的內容爲根據ID正確元素。這就是爲什麼。

如果你想避免這種情況,你可以添加點擊,而不是/

$("#right").click(function() { 

// do this 
}); 
$("#left").click(function() { 
// do this 
}); 
+0

我確實有很多元素左右不僅在頁面上,我需要某些東西像聚焦或點擊到處但不是左邊 –