将固定位置停在某个div或某个位置 [英] Stop fixed position at certain div or certain position
本文介绍了将固定位置停在某个div或某个位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要停止一个div,该div在滚动到另一个元素之前会在滚动位置上处于固定位置,基本上使它返回到某个位置的绝对位置,并且该div应该在屏幕的任何尺寸下都可以工作.我有一个带代码的jsfiddle,有两个元素,如果您知道答案,请看示例并提供帮助!
I need to stop a div which gets a fixed position on scroll before it touches another element, basically make it go back to absolute position at a certain position, and this should be working at any size of the screen. I have a jsfiddle with code and there are two elements, please see the example and help if you know the answer thanks!
var navTop = $('#nav').offset().top;
var lastMode = "absolute";
$(window).scroll(function(){
var mode;
if ($(this).scrollTop() >= navTop) {
mode = 'fixed';
} else {
mode = 'absolute';
}
if(lastMode !== mode) {
if (mode == 'fixed') {
$('#nav').css('position', 'fixed');
$('#nav').css('top', '0');
} else {
$('#nav').css('position', 'absolute');
$('#nav').css('top', navTop);
}
lastMode = mode;
}
});
https://jsfiddle.net/Zygimantas10/vro3LLu9/
让我知道是否不清楚.
推荐答案
喜欢吗?
var navTop = $('#nav').offset().top;
var navStop = $('#stop').offset().top;
var lastMode = "absolute";
$(window).scroll(function() {
var mode;
if ($(this).scrollTop() >= navTop) {
if ($(this).scrollTop() - navStop + $('#nav').height() > 0)
mode = 'absolute';
else
mode = 'fixed';
} else {
mode = 'absolute';
}
if (lastMode !== mode) {
if (mode == 'fixed') {
$('#nav').css('position', 'fixed');
$('#nav').css('top', '0');
} else {
$('#nav').css('position', 'absolute');
$('#nav').css('top', navTop);
}
lastMode = mode;
}
});
#nav {
background: rgba(0, 0, 0, 0.5);
position: absolute;
top: 200px;
width: 100px;
height: 50px;
}
#stop {
width: 100%;
background: blue;
height: 300px;
position: absolute;
top: 900px;
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body style="height:5000px;">
<div id="nav"></div>
<div id="stop"></div>
</body>
这篇关于将固定位置停在某个div或某个位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文