点击外面时隐藏下拉菜单

时间:2016-07-25 06:49:24

标签: javascript jquery drop-down-menu

我有一个带有复选框的下拉菜单。我想在用户点击外面时关闭下拉列表。

我的代码是:

<form>
<div class="multiselect">
    <div class="selectBox" onclick="showCheckboxes()">
        <select>
        </select>
    </div>
    <div class="checkboxes" id="checkboxes">
        @{ 
            if (ViewBag.DataActiveEmployee == null || ((IEnumerable<MvcApplication1.Models.ActiveUsersList>)ViewBag.DataActiveEmployee).Count() == 0)
            {
                //@:<h3>No records were processed.</h3>

            }
            else
            {
                foreach (var usr in ViewBag.DataActiveEmployee)
                {                   
                        <label id="userName">@usr.EmployeeName</label>     
                        <input class="checked" type="checkbox" name="search_emp" id="search_emp" value=@usr.EmployeeName>
                @:
        }
            }
        }

    </div>
</div>

JS

<script>
var expanded = false;
checkboxes.style.display = "none";
function showCheckboxes() {
    var checkboxes = document.getElementById("checkboxes");
    if (!expanded) {
        checkboxes.style.display = "block";
        expanded = true;
    } else {
        checkboxes.style.display = "none";
        expanded = false;
    }
}

$('multiselect').click(function () {
    $("#checkboxes").hide();
});

问题在于JavaScript的第二个功能,因为当我在外面按下时,什么也没发生。

请帮忙。

2 个答案:

答案 0 :(得分:1)

尝试使用event.target处理点击事件:

<强>更新

$(document).on('click', '.multiselect .selectBox', function(e) {
  e.stopImmediatePropagation();
  $('#checkboxes').show();
});

$('body').on('click', function(e) {  
  if (e.target.id != 'checkboxes' && $(e.target).closest('#checkboxes').length == 0) {
    $('#checkboxes').hide();
  }
});
#checkboxes,
.multiselect {
  padding:15px;
  border:1px solid #d8d8d8;
}

.selectBox { display: inline; }

#checkboxes { display:none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="multiselect">
    <div class="selectBox">
        <select>
        </select>
    </div>
    <div class="checkboxes" id="checkboxes">
        <label id="userName">Employee 1</label>     
        <input class="checked" type="checkbox" name="search_emp" id="emp_1" value="val_1">
        <label id="userName">Employee 1</label>     
        <input class="checked" type="checkbox" name="search_emp" id="emp_1" value="val_1">
    </div>
</div>

答案 1 :(得分:0)

检查目标点击dom是否为下拉列表本身

$(document).on("click", function(event){
        var $trigger = $(".checkboxes");
        if($trigger !== event.target && !$trigger.has(event.target).length){
            $(".checkboxes").hide();
        }            
    });

它应该有用。