對於我目前的項目,我想在我的DOM中製作一種固定的元素。 我沒有使用position: fixed
,因爲這個元素將會在DOM中失去它的存在,因此它的原始位置(在我看來這隻會讓事情變得更糟)。我通過向可滾動元素添加/刪除margin-top: somevalue
,每當用戶滾動並且我使用的代碼在JavaScript中成爲可能時,我就使該元素像固定元素一樣運行。使用這種方法還爲整個「交互」添加了一個漂亮的動畫。如何使用以下代碼停止「固定」元素?
我遇到的問題是,當(瀏覽器)窗口有這麼小的高度,該元素將達到頁腳,它將擴大容器,身體或任何父母在它上面。我如何防止這種情況發生?
我做了一個JSFiddle這個問題的每個例子。
$(document).ready(function() {
var topPadding = 10;
//Set the scrollable offset before starting the scroll
var scrollableTopOffset = $(".scrollable").offset().top;
$(window).scroll(function() {
/* When scrolling, determine wether the browser window still contains
\t \t scrollable: */
if (scrollableTopOffset < $(window).scrollTop()) {
//Code when scrollable is within the browser window...
//$(".shopping-cart").addClass("scrollable-fixed");
$(".scrollable").stop().animate({
marginTop: $(window).scrollTop() - scrollableTopOffset + topPadding
});
} else {
//Code when scrollable is not within the browser window...
//$(".shopping-cart").removeClass("scrollable-fixed");
$(".scrollable").stop().animate({
marginTop: 0
});
}
});
});
.some-content-block {
height: 150px;
margin-bottom: 5px;
background-color: red;
}
.scrollable {
height: 75px;
background-color: cyan;
}
footer {
height: 200px;
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="container" style="background-color: blue;">
<div class="row">
<div class="col-md-12">
<div class="some-content-block">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-10 col-sm-10 col-md-10">
<div class="col-md-4">
<div class="some-content-block">
</div>
</div>
<div class="col-md-4">
<div class="some-content-block">
</div>
</div>
<div class="col-md-4">
<div class="some-content-block">
</div>
</div>
<div class="col-md-4">
<div class="some-content-block">
</div>
</div>
<div class="col-md-4">
<div class="some-content-block">
</div>
</div>
<div class="col-md-4">
<div class="some-content-block">
</div>
</div>
<div class="col-md-4">
<div class="some-content-block">
</div>
</div>
</div>
<div class="col-xs-2 col-sm-2 col-md-2">
<div class="scrollable">
</div>
</div>
</div>
</div>
<footer></footer>
編輯:這是我撥弄SamGhatak的答案更新:JSFiddle
https://www.google.com/search?q=stop+floating+div+from+expanding+parent – mplungjan
然後你會看到使用'position'財產噸的結果。請先閱讀我的問題。我需要的一切就是在到達頁腳元素後停止添加頁邊距,並且我想知道哪一段javascript代碼可以確定用戶到達頁腳,然後停止添加頁邊距。 – Barrosy
從小提琴,它看起來確定...你想糾正哪一部分? – SamGhatak