簡體   English   中英

修復了滾動div內的div

[英]Fixed div inside scrolling div

我需要使我的網站的主要980px width500px height (class =“main”)只有當鼠標位於滾動div並且height of 1500pxwidth of 100%時才能修復(class =“ container-scroll“),即height of 500px.其他div內height of 500px. (類= “容器”)

很困惑吧?

我做了一個小提琴,我幾乎在那里,問題是,如果我設置主要固定,它將滾動頁面,而不僅僅是在div內

這是我的小提琴: https//jsfiddle.net/8oj0sge4/1/embedded/result/

HTML:

<div id="wrapper">
    <div class="container">
        <div class="container-scroll">
            <div class="main">

            </div>
        </div>
    </div>
</div>

CSS:

    #wrapper {
        width: 100%;
        height: 1500px;
        border: 1px solid red;
        padding-top: 380px;
    }
    #wrapper .container {
        border: 1px solid green;
        width: 100%;
        height: 500px;
        overflow: scroll;
    }
    #wrapper .container-scroll {
        height: 1500px;
        width: 100%;
        border: 1px solid yellow;
    }
    #wrapper .main {
        width: 980px;
        height: 500px;
        background: black;
        overflow: scroll;
        /*position: fixed;*/
    }

如果我正確理解這一點,你希望主div保持在父div的頂部?

小提琴: https//jsfiddle.net/8oj0sge4/3/完整

做出的改變:

  • #wrapper .main :添加position:absolute (“固定”到父級)
  • #wrapper .container-scroll :添加position: relative (確定要“修復”的父級)
  • 為主div添加了一個id(為方便起見)

JavaScript代碼:

var main = document.getElementById('main-site');
var maxTop = main.parentNode.scrollHeight-main.offsetHeight; // Make sure we don't go outside the parent

main.parentNode.parentNode.onscroll = function() {
   main.style.top = Math.min(this.scrollTop,maxTop) + "px";
}

沒有純CSS可以做到這一點,但你可以用一些Javascript解決它。

一個解決方案可能是禁用內部div上的滾動,如果已經在#wrapper上啟動了#wrapper ,這是在這個小提琴上演示的:

https://jsfiddle.net/qmjmthbz/

這是代碼:

var wrapper = $('#wrapper');
var container = $('.container');
var timer;

// Listen to mouse scroll events
$('body').on('mousewheel', function(e) {
    var target = $(e.target);
    /* If the scroll is initiated from the #wrapper,
       disable scroll on the container and re-enable it
       100ms after the last scroll event */
    if (target[0] === wrapper[0]) {
        container.addClass('no-scroll');
        clearTimeout(timer);
        timer = setTimeout(function() {
            container.removeClass('no-scroll');
        }, 100);
    }
});

注意:使用jQuery實現這一點是沒用的,但我在火車站趕緊去。 當我能找到更多時間時,我會提供更好的代碼:-)

基本上我認為你不能使div滾動,因為div的內容不超過div的高度。 為了使div能夠滾動,內容實際上應該超過div的高度。

嘗試給div設置100px的高度,並插入足夠大的文本以超過100px高度,從而使div可滾動,然后嘗試是否可以實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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