我想在它下方滚动时将某个div粘贴到顶部。经过一番研究,我发现了这个解决方一切正常,除了在滚动它时div的内容向左移动一点
的javascript
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').addClass('stick');
} else {
$('#sticky').removeClass('stick');
}
}
$(function () {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
CSS
#sticky {
padding: 0.5ex;
font-size: 2em;
border-radius: 0.5ex;
}
#sticky.stick {
position: fixed;
top: 0;
z-index: 10000;
border-radius: 0 0 0.5em 0.5em;
}
HTML
<hr />
<div id="sticky-anchor"></div>
<div id="sticky">
<center>Unternehmen Leistungen Kunden Stärken</center>
<hr /></div>
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').addClass('stick');
} else {
$('#sticky').removeClass('stick');
}
}
$(function() {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
#sticky {
padding: 0.5ex;
font-size: 2em;
border-radius: 0.5ex;
}
#sticky.stick {
position: fixed;
top: 0;
z-index: 10000;
border-radius: 0 0 0.5em 0.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr />
<div id="sticky-anchor"></div>
<div id="sticky">
<center>Unternehmen Leistungen Kunden Stärken</center>
<hr />
</div>
答案 0 :(得分:0)
您必须将div
居中以防止这种转变。要将div
与position:fixed;
居中,您需要将left
和right
设置为0。
CSS
#sticky.stick {
position: fixed;
top: 0;
left:0;
right:0;
z-index: 10000;
}
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').addClass('stick');
} else {
$('#sticky').removeClass('stick');
}
}
$(function() {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
&#13;
#sticky {
position:relative;
padding: 0.5ex;
font-size: 2em;
text-align:center;
}
#sticky.stick {
position: fixed;
top: 0;
left:0;
right:0;
z-index: 10000;
}
.content {
height:1000px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr />
<div id="sticky-anchor"></div>
<div id="sticky">
Unternehmen Leistungen Kunden Stärken
<hr />
</div>
<div class="content"></div>
&#13;