【问题标题】:jQuery issue: body overflow vs body marginjQuery问题:正文溢出与正文边距
【发布时间】:2018-01-11 11:10:03
【问题描述】:

大家好!

当我单击一个 div 时,我希望将溢出的 body 隐藏起来,并为滚动条宽度的 body 添加一个右边距。这是我的 jQuery:

var getScrollbarWidth = function () {
    var scrollElement = document.createElement("div"); // Create element
    scrollElement.addClass("scrollbar-element"); // Apply predefined style

    document.body.appendChild(scrollElement); // Add element to page
    var scrollbarWidth = scrollElement.offsetWidth - scrollElement.clientWidth; // Subtract width without scrollbar from width with scrollbar
    document.body.removeChild(scrollElement); // Remove element from page
    return scrollbarWidth;
  };    

$(".thumbnail").on("click", function () {
    $(".project-wrap").addClass("project-open");
    $("body").attr("margin-right", getScrollbarWidth() + "px");
    $(".project-button").attr("margin-right", getScrollbarWidth() + "px");
    $("body").addClass("body-overflow");
  }

还有css:

.body-overflow
  overflow: hidden !important
.project-open
    display: block !important

问题是如果 "$("body").addClass("body-overflow");"到底是不行,但是如果是在缩略图点击功能的第一行,则不应用body margin。

【问题讨论】:

    标签: javascript jquery overflow margin


    【解决方案1】:

    在添加body-overflow 类之前,尝试将滚动条宽度存储在变量中。 喜欢:

    $(".thumbnail").on("click", function () {
        var scrollbarWidth = getScrollbarWidth();
    
        $("body").addClass("body-overflow");
        $("body").attr("margin-right", scrollbarWidth + "px");
        $(".project-wrap").addClass("project-open");
        $(".project-button").attr("margin-right", scrollbarWidth + "px");
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-04
      • 2017-03-08
      • 2011-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      相关资源
      最近更新 更多