jQuery 问题:正文溢出与正文边距

jQuery issue: body overflow vs body margin

大家好!

当我单击 div 时,我希望主体的溢出部分隐藏起来,并向主体添加滚动条宽度的右边距。这是我的 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");”到最后还是不行,但是如果是在thimbnail click函数的第一行,那么body margin就不适用了。

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

$(".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");
});