2015-07-01 43 views
1

我創建了一個自定義的下拉列表,除了我希望下拉被隱藏(slideUp),如果沒有下拉div和所有的孩子被點擊,一切都很好。爲了更加清晰,我打算隱藏下拉列表,如果不是下拉菜單(單擊主體或文檔上的任何地方,除了下拉菜單及其子菜單)。下面是我的片段,但是,我的嘗試可悲的是不工作。任何幫助,建議,建議,想法,線索非常感謝。謝謝!當點擊除指定的div以外,然後隱藏下拉

$(document).ready(function(){ 
 
    $(".with_dpx").click(function(e){ 
 
     $(".dpx", this).slideDown(); 
 
     e.preventDefault(); 
 
    }); 
 
    $(document).on("click", function(event){ 
 
     if(event.target.is(".dpx")){ 
 
      alert("asdas"); 
 
     } 
 
    }); 
 
    
 
});
.thehide{display: none;} 
 
.dpx{ 
 
    padding: 0px; 
 
    margin: 0px; 
 
    list-style: none; 
 
    position: absolute; 
 
    z-index: 9999; 
 
    padding: 10px; 
 
    background: #fff; 
 
    margin-top: 20px; 
 
    box-shadow: 0 0.5px 0 0 #ffffff inset, 0 1px 2px 0 #B3B3B3; 
 
} 
 
.dpx li{list-style: none;} 
 
.dpx li{ 
 
    padding: 5px 8px!important; 
 
    font-size: 15px; 
 
    color: #555 !important; 
 
    display: block !important; 
 
    clear: both; 
 
    float: none; 
 
    text-transform: uppercase; 
 
    border: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="menu"> 
 
    <a href="#" class="with_dpx"> 
 
    Menu 1 
 
    <ul class="thehide extend clear display_table dpx" id="test"> 
 
     <li>hr approver</li> 
 
     <li>manager approver</li> 
 
     <li>attendance approver</li> 
 
    </ul> 
 
    </a> 
 
    <a href=="#"> 
 
    Menu 2 
 
    </a> 
 
</div>

回答

1

你可以試試這個

$(document).mouseup(function (e) 
{ 
var container = $("YOUR CONTAINER SELECTOR"); 

if (!container.is(e.target) // if the target of the click isn't the container... 
    && container.has(e.target).length === 0) // ... nor a descendant of the container 
{ 
    container.hide(); 
} 
}); 
+1

謝謝你的工作就像魅力:) –

+1

沒有問題:),很高興它有助於交配 –

2

你可以試試這個: -

$(document).on("click", function(event){ 
    if($(event.target).is(".dpx")||$(event.target).closest(".dpx").length){ 
     //or this will also work 
     //$(event.target).parents(".dpx").length   
     alert("asdas"); 
    } 
});