【问题标题】:How to disable scroll when a div is shown?显示div时如何禁用滚动?
【发布时间】:2017-09-18 00:50:36
【问题描述】:

我想在显示 div 时禁用页面滚动,因为它是一个画廊,滚动会破坏它的功能。

            $(document).ready(function () {
                if($("#lightbox").css('display') == 'none') {
                    console.log("not hidden");
                    document.body.style.overflow = "auto";
                } else if($("#lightbox").css('display') == 'block') {
                    document.body.style.overflow = "hidden";
                    console.log("hidden");
                }
            });

我可以在控制台中看到“未隐藏”,这意味着该功能有效,但是当我单击打开图库(显示 div)时它不会隐藏滚动。我试过只用别的,同样的东西。

提前致谢。

【问题讨论】:

标签: jquery html css dom


【解决方案1】:

里面的代码:

$(document).ready(function () {

表示您的页面已完全加载,它将被执行,并且它只是一个 1-time 事件。

所以你必须在点击“打开相册”按钮时绑定一个事件,检查lightbox的状态:

$("#openGaleryId").click(function(){
    if($("#lightbox").css('display') == 'none') {
       console.log("not hidden");
       document.body.style.overflow = "auto";
    } else if($("#lightbox").css('display') == 'block') {
        document.body.style.overflow = "hidden";
        console.log("hidden");
    }
});

【讨论】:

  • 我已绑定为来自<li><a href="css/art1.jpg" class="gallery" data-lightbox="portfolio"><img src="css/art1.jpg" class="art" /></a>$(".gallery").click,但没有任何反应。
  • 我认为if($("#lightbox").css('display') == 'none') 语句存在问题,因为控制台显示 div 存在但源代码状态为display: none;。也许我应该以不同的方式编写语句,但我该怎么做。
  • 也许这个事件在 #lightbox 改变之前就被触发了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 2012-02-24
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
  • 2014-05-26
相关资源
最近更新 更多