2014-03-25 22 views
1

我寫的這個js + HTML/CSS http://jsfiddle.net/A1ex5andr/xpRrf/ Tt的工作,它應: 開/關上.advSearch .advSearch-btn 收盤.advSearch-control .canc 但我不能讓它關門,如果鼠標點擊任何地方出<div class="advSearch">JS顯示/隱藏/關閉,如果出了格

HTML部分

<div class="advSearch"> 
    <span class="advSearch-btn">Advanced Search</span> 
    <div class="advSearch-container"> 
    <div class="col left"> 
     <h3>Customer</h3> 
     <form action=""> 
     <label><h4>First Name</h4> <input type="text"> </label> 
     <label><h4>Last Name</h4> <input type="text"> </label> 
     <label><h4>Email</h4> <input type="text"> </label> 
     <label><h4>Phone</h4> <input type="text"> </label> 
     </form> 
    </div> 
    <div class="col central"> 
     <h3>Address</h3> 
     <form action=""> 
     <label><h4>Adsress</h4> <input type="text"> </label> 
     <label><h4>City</h4> <input type="text"> </label> 
     <label><h4>State</h4> <input type="text"> </label> 
     <label><h4>Zip</h4> <input type="text"> </label> 
     </form> 
    </div> 
    <div class="col right"> 
     <h3>Other</h3> 
     <form action=""> 
     <label><h4>Policy</h4> <input type="text"> </label> 
     <label><h4>App ID</h4> <input type="text"> </label> 
     <label><h4>Quote</h4> <input type="text"> </label> 
     <label><h4></h4> <input type="text"> </label> 
     </form> 
    </div> 
    <div class="advSearch-control"> 
    <button class="canc">Cancel</button> 
    <button class="srch">Search</button> 
    </div> 
    </div> 
</div> 

JS的作品

的名

我試圖盡收在鼠標點擊出OUF: (在運行的代碼註釋)

   $(document).click(function() { 
       if (container.is(":visible")) { 
        container.fadeOut(300); 
       } else { 
        e.stopPropagation(); 
        console.log('its stoped'); 
       } 
      }); 

   $(document).click(function(event) { 
       if ($(event.target).parents().index(container) == -1) { 
        if (container.is(":visible")) { 
         container.hide() 
        } 
       } 
      }) 

的問題是什麼我做錯了嗎? 預先感謝您。

+0

取消註釋第一個工作正常,它淡出開放的div。究竟是什麼問題? – StephenRios

+1

與此處同樣的問題可能,聽起來類似? http://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it –

+1

他想關閉高級搜索屏幕的問題,如果他點擊該屏幕之外。 –

回答

3

試試這個。請注意,高級搜索處於打開狀態時,您無需創建事件。只是把它正常加載:

$(document).click(function(e) { 
    if($(e.target).parents('.advSearch').first().length == 0) 
     container.fadeOut(300); 
}); 
+0

它的工作原理, 我已經添加了幾行以保持按鈕隱藏順序的事件。 $('。canc')。css('display','none'); $('。srch')。css('display','none');' – A1exandr

+0

您是否會如此善意地談談它是如何工作的? – A1exandr

+1

我們在這裏做的是將點擊事件綁定到文檔本身,以便註冊這些點擊並使用它來檢查某些內容。 'e.target'指向啓動事件的元素。 'parents()'從目標元素開始導航所有的父元素,然後我們過濾它以匹配託管搜索表單的容器的類。 'first()'動作是一個過濾器,一旦它找到過濾器就會停止,這是爲了縮短jQuery所做的內部'while'。最後,我們通過檢查結果對象數組的長度來檢查是否找到了匹配項。 – SparoHawk