Wil*_*yan 7 javascript css jquery scroll jquery-animate
我按照教程来获得一个粘性的"返回顶部"按钮,一旦向下滚动就会出现.出于某种原因,在页面首次加载后,当您位于页面顶部时,它会显示.如果向下滚动,然后一直向上,它就会消失(应该如此).但最初它表现不佳.任何的想法?
这是我正在使用它的实时页面,你可以在右下角看到它:http://willryan.us
HTML
<a href="#" class="go-top" style="display: inline;">Back to top</a>
<script>
$(document).ready(function() {
// Show or hide the sticky footer button
$(window).scroll(function() {
if ($(this).scrollTop() > 200) {
$('.go-top').fadeIn(500);
} else {
$('.go-top').fadeOut(300);
}
});
// Animate the scroll to top
$('.go-top').click(function(event) {
event.preventDefault();
$('html, body').animate({scrollTop: 0}, 300);
})
});
</script>
Run Code Online (Sandbox Code Playgroud)
CSS
.go-top {
position: fixed;
bottom: 0.75em;
right: 0.5em;
text-decoration: none;
color: white;
background-color: rgba(0, 0, 0, 0.25);
font-size: 12px;
padding: 10px;
display: none;
margin: 0;
}
.go-top:hover {
background-color: rgba(0, 0, 0, 0.6);
color: white;
text-decoration: none;
}
Run Code Online (Sandbox Code Playgroud)
ntg*_*ner 12
更改您的HTML
<a href="#" class="go-top" style="display: inline;">Back to top</a>
Run Code Online (Sandbox Code Playgroud)
至
<a href="#" class="go-top" style="display: none;">Back to top</a>
Run Code Online (Sandbox Code Playgroud)
这将首先隐藏您的按钮,直到您滚动.
它正在显示,因为您尚未触发滚动事件,以使该逻辑运行以隐藏/显示它
<script>
$(document).ready(function() {
function checkPosition() {
if ($(this).scrollTop() > 200) {
$('.go-top').fadeIn(500);
} else {
$('.go-top').fadeOut(300);
}
}
// Show or hide the sticky footer button
$(window).scroll(checkPosition);
// Animate the scroll to top
$('.go-top').click(function(event) {
event.preventDefault();
$('html, body').animate({scrollTop: 0}, 300);
})
checkPosition();
});
</script>
Run Code Online (Sandbox Code Playgroud)
这个新的重构器会checkPosition在页面加载时至少触发一次,以确保按钮淡出.另一种解决方案是display: none;在元素上设置CSS,因此默认情况下它是隐藏的,之后只能通过javascript显示