[英]jQuery Stop content from jumping when overflow hidden
The default size of a scrollbar is 17px in width, however its better to let the browser calculate the exact width and then use it.滚动条的默认宽度为 17px,但是最好让浏览器计算出准确的宽度然后使用它。
// Calculating the exact width of the browser scrollbar
let scrollbarWidth=(window.innerWidth-$(window).width());
// then when needed to perform a click action just add this below it:
$("body").css("overflow","hidden");
$("body").css("padding-right", scrollbarWidth +"px");
Try using box-sizing: border-box;
尝试使用box-sizing: border-box;
in your body.在你的身体里。
Here in this demo I set the body width to (100vw + 1px) so that it will engage the horizontal scrollbar.在此演示中,我将主体宽度设置为(100vw + 1px) ,以便它与水平滚动条接合。 When you click the button, it will add the style as you showed (hiding the scrollbar and adding margin to the body).当您单击该按钮时,它将添加您显示的样式(隐藏滚动条并向主体添加边距)。
I added borders to the button to show it correctly aligns to the right edge as intended.我为按钮添加了边框,以显示它按预期正确对齐到右边缘。
$(document).ready(function() { console.log($(document).width(), window.innerWidth); var scrollbarWidth = ($(document).width() - window.innerWidth) + "px"; $(document).on('click', '.is-open', function() { console.log(scrollbarWidth); if ($(this).hasClass("is-open")) { $("body").css("overflow", "hidden"); $("body").css("padding-right", scrollbarWidth); } }); });
body{ width: calc(100vw + 2px); box-shadow: inset 0 0 2px red; margin: 0; box-sizing: border-box; }.is-open{ cursor: pointer; border: solid green; padding: 2px 10px; font-size: 2rem; text-align: right; }.buttoncontainer{ display: block; text-align: right; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <p>Clicking the button will hide the scrollbar and add a padding-right to body</p> <div class="buttoncontainer"> <button class="is-open">Click here</button> </div> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.