简体   繁体   中英

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.

// 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; in your body.

Here in this demo I set the body width to (100vw + 1px) so that it will engage the horizontal scrollbar. 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM