我正在尝试使用通过按下空下拉列表切换的div来创建多选下拉列表的错觉。它工作正常,但我希望能够在div外点击时隐藏它。我该怎么做呢?我使用以下代码:
<script src="../js/jqGlobal.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".testColor").click(function () {
$("#exampleDiv").toggle();
});
$("#exampleDiv").blur(function () {
$("#exampleDiv").toggle();
});
});
</script>
<style type="text/css">
#exampleDiv
{
position: absolute;
top:22px;
left: 0px;
width:198px;
height:150px;
overflow-y: scroll;
overflow-x: hidden;
border: 1px solid #7F9DB9;
display: none;
}
</style>
<div style="position:relative;">
<asp:DropDownList ID="DropDownList1" runat="server" Width="200" class="testColor">
</asp:DropDownList>
<div id="exampleDiv">
<asp:CheckBox ID="CheckBox2" runat="server" />
<br />
<asp:CheckBox ID="CheckBox3" runat="server" />
<br />
<asp:CheckBox ID="CheckBox4" runat="server" />
<br />
<asp:CheckBox ID="CheckBox5" runat="server" />
<br />
<asp:CheckBox ID="CheckBox6" runat="server" />
<br />
<asp:CheckBox ID="CheckBox7" runat="server" />
<br />
<asp:CheckBox ID="CheckBox8" runat="server" />
<br />
<asp:CheckBox ID="CheckBox9" runat="server" />
<br />
<asp:CheckBox ID="CheckBox10" runat="server" />
<br />
<asp:CheckBox ID="CheckBox11" runat="server" />
<br />
<asp:CheckBox ID="CheckBox12" runat="server" />
<br />
</div>
</div>
答案 0 :(得分:1)
var element = $("#exampleDiv");
$(document).bind('mouseup', function (e){
if (element.has(e.target).length === 0)
$(element).hide();
});
$(element).click(function(){
$(element).show();
})
答案 1 :(得分:0)
您可以尝试.mouseout()而不是.blur()
答案 2 :(得分:0)
点击页面上隐藏div的任何位置,并在点击testColor时取消点击传播到父元素
function cancelBubleEv(e)
{
e = e||event;
e.stopPropagation? e.stopPropagation() : e.cancelBubble = true;
}
$(document).ready(function () {
$(document).click(function () {
$("#exampleDiv").hide();
});
$(".testColor").click(function (e) {
$("#exampleDiv").toggle();
cancelBubleEv(e);
});
$("#exampleDiv").click(function (e) {
cancelBubleEv(e);
});
});
编辑:
单击复选框时取消事件传播