外部点击

时间:2017-06-08 15:56:06

标签: javascript jquery html

我得到了以下HTML:

<div id="otherdiv"></div>
 <div class="overlay">
  <div class="menu">
    <ul>
      <li><a href="#">Val1</a></li>
     <li><a href="#">Val2</a></li>
    </ul>
   </div>
</div>

和JS代码:

$(document).ready(function(){
$('#otherdiv').on('mouseup', function(e){
     var left  = e.clientX  + "px";
     var top  = e.clientY  + "px";
     var div = $('.overlay');
     div[0].style.left = left;
     div[0].style.top = top;
     $(".overlay").show(200);
   });
 $(document).on('click', function(e) {
    $('.overlay').hide(200);
  });
});

我需要在用户点击其外部时隐藏我的.overlay,并在用户点击#otherdiv时显示该document。当我将事件附加到otherdiv并点击const wrapGenerator = gen => (...args) => { const it = gen(...args); let previous, current; return { next: () => { const r = it.next(); previous = current; current = r.value; return r; }, previous: () => ({ value: previous }) }; }; const gen = wrapGenerator(function * () { yield * [0, 1, 2, 3]; }); const it = gen(); console.log(it.next().value); console.log(it.next().value); console.log(it.previous().value);时,我的叠加显示然后立即隐藏。如何解决这种行为?谢谢。

2 个答案:

答案 0 :(得分:0)

document.click上检查event.target是不是#otherdiv还是不是#otherdiv的孩子而event.target不是.overlay或者它的孩子然后隐藏$(".overlay")

示例摘要。为#otherdiv.overlay添加了css for demo&gt;只有当用户点击外部时才会隐藏叠加层

$(document).ready(function(){
 $('#otherdiv').on('mouseup', function(e){
      e.preventDefault();
     var left  = e.clientX  + "px";
     var top  = e.clientY  + "px";
     var div = $('.overlay');
     div[0].style.left = left;
     div[0].style.top = top;
     $(".overlay").show(200);
   });
  $(document).on('click', function(e) {
  
  if( ! $('#otherdiv').is(e.target)&&    $('#otherdiv').has(e.target).length === 0 && !$('.overlay').is(e.target)  && $('.overlay').has(e.target).length === 0 ){
    $('.overlay').hide(200);
  }
   
  });
});
#otherdiv{
 width:100%;
 height:50px;
 background:#ddd;
}

.overlay{
  
 background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="otherdiv">
  click here to show
</div>
 <div class="overlay">
  <div class="menu">
    <ul>
      <li><a href="#">Val1</a></li>
     <li><a href="#">Val2</a></li>
    </ul>
   </div>
</div>

答案 1 :(得分:0)

同时点击

clickmouseup个事件,请点击此处了解更多信息 - https://www.quirksmode.org/dom/events/click.html

关于jQuery如何处理动画的一个有趣的事情是它将事物放入队列中 - 因此,hide()动画排队等待show()后的200毫秒,即使这两个函数同时触发时间。

相反,我建议只使用一次点击事件 -

$(document).on('click', function(e) {
    if(event.target.id == 'otherdiv' && !$('.overlay').is(":visible")) {
       //do stuff to show
    }
    else if($('.overlay').is(":visible")) {
        $('.overlay').hide(200);
    }
});

第一次if检查以确保点击了标识为otherdiv的元素,并且当前无法看到叠加层。下一个if检查是否有点击并且叠加层可见。

相关问题