单击任何屏幕位置关闭菜单

时间:2016-11-24 18:02:22

标签: javascript jquery html css

有一个打开菜单的脚本,点击'li'元素后关闭,如何通过点击屏幕上的任何地方关闭它?

 a, .a {
        color: white;
    }

    a:hover, a:focus {
        color: white;
        text-decoration: none;
    }

这就是我的HTML:

$(function() {
  $('.drop-down-input').click(function() {
  $('.drop-down-input.selected').removeClass('selected'); // Forget the previous selection
  $(this).addClass('selected');
  $(this).find(".dropdown-list").show();
});

$(document).on("click", ".drop-down-input.selected li",
  function(e) {
    e.stopPropagation();
    $('.drop-down-input.selected .dropdown-list').hide().siblings().val($(this).html());
  });
});

2 个答案:

答案 0 :(得分:2)

这是一个有效的解决方案。希望它有所帮助:)



$( document ).ready(function() {
    
    // change from grey to blue color input
    
    
  $(".styled-input-container input").focus(function () {
     $id = this.id;
     $idgen = '#' + $id;
     //console.log($idgen);
     
     $($idgen).closest( "div" ).addClass('focused');
    });
    
    $(".styled-input-container input").blur(function() {
        $('.styled-input-container').removeClass('focused');
        
    });
  
  
    
    //open % close ul list input
    
   $(function() {
  $('.drop-down-input').click(function() {
  $('.drop-down-input.selected').removeClass('selected'); // Forget the previous selection
  $(this).addClass('selected');
  $(this).find(".dropdown-list").show();
});

$(document).on("click", ".drop-down-input.selected li",
  function(e) {
    e.stopPropagation();
    $('.drop-down-input.selected .dropdown-list').hide().siblings().val($(this).html());
  });
});

$(document).mouseup(function (e){
    var container = $(".dropdown-list");

    if (!container.is(e.target)
        && container.has(e.target).length === 0)
    {
        container.hide();
    }
});
   

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="styled-input-container">
                       <input id="simple_1" placeholder="input text" type="text">
                   
                   </div>
                   <div class="separator"></div>
                   <div class="styled-input-container drop-down-input">
                       <input id="simple_2" class="drop-down-select" placeholder="input text" type="text">
                       <ul class="dropdown-list">
                           <li>eeee</li>
                           <li>xxxx</li>
                           <li>xxxx</li>
                           <li>xsssxxx</li>
                       </ul>
                   </div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

只需在所有dom上添加一个监听器:

$(document).on('click', ':not(.drop-down-input.selected li)',function() {/* Close all open menus  */});

看到你可以忽略带有:not选择器的li元素,以防止点击那些元素。