我的网页中心有一张图片。一旦用户滚动并且图像到达窗口顶部,我就会尝试将图像固定到页面顶部,以便它随页面滚动。
然而,当用户滚动时,图像当前会跳到页面顶部,而不是在它碰到窗口顶部时粘住。虽然我希望图像在用户在页面上时保持固定在顶部,但在刷新页面时它仍保持固定状态!
似乎无法弄清楚这一点 - 请帮忙!
index.html
<img src="./assets/img/logo.png" class="logo" alt="Logo">
style.css
.logo {
width: 500px;
display: block;
position: absolute;
top: 200px;
left: 0;
right: 0;
margin: auto;
}
main.js
$(function() {
var boxInitialTop = $('.logo').offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() > boxInitialTop) {
$('.logo').css({position: 'fixed', top: '0px'});
} else {
$('.logo').css({position: 'absolute'});
}
});
});
答案 0 :(得分:3)
我认为您需要做的就是在向下滚动时重置初始最高值:
var boxInitialTop = $('.logo').offset().top;
$(window).scroll(function() {
if ($(window).scrollTop() > boxInitialTop) {
$('.logo').css({
position: 'fixed',
top: '0px'
});
} else {
$('.logo').css({
position: 'absolute',
top: '200px' // add this to "reset" the top to it's original (that you set in your css)
});
}
});
&#13;
body {height:2000px;}
#test {
height: 400px;
position: relative;
}
.logo {
width: 500px;
display: block;
position: absolute;
top: 200px;
left: 0;
right: 0;
margin: auto;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<img src="http://lorempixel.com/400/200/city/" class="logo" alt="Logo">
</div>
&#13;
答案 1 :(得分:2)
您的代码有效。
您只需重置top
部分中的else
值即可。
这样它就会保留0px
,因为它是以if
部分的方式设置的。
答案 2 :(得分:1)
您需要将元素的原始位置放回到它开始的位置(在else之后)。元素返回position:absolute
后,您需要确保它的top
属性返回200px
,否则它仍将保留fixed
时设置的值。 1}}即0
。
见下文:
$(function() {
var boxInitialTop = $('.logo').offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() > boxInitialTop) {
$('.logo').css({position: 'fixed', top: '0px'});
} else {
$('.logo').css({position: 'absolute', top : boxInitialTop+'px'});
}
});
});
&#13;
答案 3 :(得分:0)
$ ( function () {
var boxInitialTop = $ ( '.logo' ). offset (). top ;
$ ( window ). scroll ( function () {
if ( $ ( window ). scrollTop () > boxInitialTop ) {
$ ( '.logo' ). css ({ position : 'relative' , top : '0px' });
} else {
$ ( '.logo' ). css ({ position : 'absolute' });
}
});
});