2
大家好!jQuery問題:body overflow vs body margin
當我點擊一個div時,我想讓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
的問題是,如果 「$(」 身體 「)addClass(」 體溢出 「);」最後,它不起作用,但如果它位於第一行的伸縮點擊函數上,則不應用身體邊距。