簡體   English   中英

jQuery 在隱藏溢出時停止內容跳轉

[英]jQuery Stop content from jumping when overflow hidden

滾動條的默認寬度為 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");

嘗試使用box-sizing: border-box; 在你的身體里。

在此演示中,我將主體寬度設置為(100vw + 1px) ,以便它與水平滾動條接合。 當您單擊該按鈕時,它將添加您顯示的樣式(隱藏滾動條並向主體添加邊距)。

我為按鈕添加了邊框,以顯示它按預期正確對齊到右邊緣。

 $(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM