【问题标题】:Return scrollbar when user clicks outside of popup to close it当用户在弹出窗口之外单击以将其关闭时返回滚动条
【发布时间】:2018-11-05 23:35:31
【问题描述】:

我有 jQuery 代码在弹出模式打开时删除滚动条。因此,当我需要关闭弹出窗口时,滚动条需要再次出现,并且该功能按预期工作,除了一件事:如果用户单击弹出窗口之外的其他位置,它将关闭,但滚动条仍然隐藏。只有在单击关闭图标时才能完全按预期工作。

当用户在弹出框外点击时,是否有可能设置自动溢出滚动?即不只是在关闭图标上?

 $(document).ready(function () {
 $("button#mainbtn").click(function (){
     $('body').css('overflow', 'hidden');  
 });

 $(document).on('click', '.closer',  function (){
     $('body').css('overflow', 'auto'); 
 });
 });


 <div id="myModal" class="modal" >
 <div class="modal-content">
 <div class="closer">&times;</div>
 </div>
 </div>

打开模态框的代码:

 var modal = document.getElementById('myModal');
 var btn = document.getElementById("mainbtn");
 var span = document.getElementsByClassName("closer")[0];
 btn.onclick = function() {
  modal.style.display = "block";
 }

span.onclick = function() {
modal.style.display = "none";
}

window.onclick = function(event) {
if (event.target == modal) {
    modal.style.display = "none";
}
}

css:

 .modal {
  display: none; 
  z-index: 100; 
  padding-top: 100px; 
  position:fixed;
  top: 0;
  width: 100%;
  height: 100%; 
  }


.modal-content {
background-color: #f2f2f2;
margin: auto;
position:relative;
width: 60%;
height:90%;
  transition: all 5s ease-in-out;
}

.closer {
top:0px;
right:20px;
 color: #00284d;
position:absolute;
font-size: 45px;

}

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    由于您附加了一个事件来关闭模式,如果他们在外部单击,您可以在隐藏模式后将溢出设置为自动。

    window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
        $('body').css('overflow', 'auto'); 
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以创建$("html").click(function() 并检查您的弹出窗口是可见还是隐藏。每次点击整个页面时都会执行该函数

      $("html").click(function() {
        if($('.popup').is(":visible")){
        alert("visible: dont show scroll")
        }
        else{
        alert("hidden: show scroll")
        }
      });
      
      $("button").click(function() {
         $('.popup').toggle();
        });
      body{
      background-color: blue;
      height; 1000px;
      width: 1000px;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <body>
      <div class="popup">popup</div>
      <button>toggle popup</button>
      </body>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-15
        • 1970-01-01
        • 2012-12-21
        • 2018-08-20
        • 2012-08-28
        • 1970-01-01
        • 1970-01-01
        • 2021-11-21
        相关资源
        最近更新 更多