2017-04-11 41 views
2

#container(位置:相對)裏面我有2個div:兩者都是50%寬,#第一個非常高(位置:相對),#第二個至少是2000px高。如何停止比窗口高度更長的滾動div?

有沒有什麼辦法讓#second停止滾動時底部到達,但繼續滾動其他內容?如果沒有製作額外的父母div,它會很棒。 小提琴:實現這個https://jsfiddle.net/Moor/ha4zybpb/

#container{ 
 
    position:relative; 
 
} 
 
#first{ 
 
    width:50%; 
 
    background:#333; 
 
    height:10000px; 
 
} 
 
#second{ 
 
    position:absolute; 
 
    right:0; 
 
    top:0; 
 
    width:50%; 
 
    height:2000px; 
 
    background:limegreen; 
 
}
<div id="container"> 
 
    <div id="first"></div> 
 
    <div id="second"></div> 
 
</div>

+0

你開到JS或jQuery的解決方案? – sol

回答

1

一種方法是使用position:sticky - 但請務必檢查browser compatability它符合您的要求。

*{margin:0;padding:0;} 
 
#first{ 
 
    background:#333; 
 
    display:inline-block; 
 
    height:10000px; 
 
    vertical-align:bottom; 
 
    width:50%; 
 
} 
 
#second{ 
 
    background:linear-gradient(0deg,#f00,#090); 
 
    bottom:0; 
 
    display:inline-block; 
 
    height:2000px; 
 
    position:sticky; 
 
    vertical-align:bottom; 
 
    width:50%; 
 
}
<div id="container"><div id="first"></div><div id="second"></div></div>

+0

Holy Coyier,好像我完全失去了時間,我從未聽說過他們增加了這個職位。我會測試它,但似乎現在不夠安全使用它http://caniuse.com/#search=position%3Asticky –

0

這不是一個完整的答案,但它可能會幫助你對你的方式 - 檢查滾動位置和視口的高度,並把它比作第二個元素的高度 -

檢查這個小提琴爲我的例子。用jQuery做

updated fiddle

$(document).ready(function() { 
console.log("ready!"); 
var secondHeight = $('#second').height(); 
console.log(secondHeight); 

var stopper = 0; 

$(window).scroll(function (event) { 
var scroll = $(window).scrollTop(); 
var viewportHeight = $(window).height(); 
    // Do something 
    console.log(scroll+viewportHeight); 



    if(secondHeight <= scroll+viewportHeight) { 
    console.log('stop it here'); 
    stopper = 1; 
    } else { 
    stopper = 0; 
    } 
    console.log(stopper); 

    if(stopper == 1) { 
    $('#second').css('position','fixed'); 
    console.log('making it fixed'); 
    } else { 
    $('#second').css('position','absolute'); 
    console.log('making it absolute'); 
    } 


    }); 


}); 
+0

謝謝,這是一個有趣的解決方案,將試用它。 –

1

一個jQuery的 「粘性」 的解決方案..

https://jsfiddle.net/cusjptLr/4/

var sh = $('#second').height(); 
$(window).scroll(function(){ 
    if (($(window).scrollTop() + $(window).innerHeight()) >= sh) { 
    $('#second').addClass("sticky"); 
    } 
}); 

#second.sticky { 
    position: fixed; 
    bottom: 0; 
    top: initial; 
} 
+0

希望避免使用腳本,但似乎是唯一的方法。謝謝! –

相關問題