大家好!
当我点击一个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");“在最后是不起作用的,但如果它位于thimbnail click函数的第一行,则不会应用正文边距。
发布于 2017-08-04 01:39:45
在添加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");
});https://stackoverflow.com/questions/45491097
复制相似问题