对于我当前的元素,我想在我的 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
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>
编辑:这是我的 fiddle 更新了 SamGhatak 的答案:JSFiddle
最佳答案
我想我在这里找到了解决方案:
https://jsfiddle.net/rv4mg8uq/2/
在此处添加此代码:
if(($('footer').offset().top -scrollableTopOffset +topPadding)<$(window).scrollTop()){
//do nothing
}
关于javascript - 如何使用以下代码停止 "fixed"元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36933520/