我创建了一个方法,每次单击它时都会转到页面顶部。 问题是,我希望仅当您已经向下滚动时才显示此按钮,而不仅仅是默认按钮。我该如何定义它?这是我的代码:
显示/隐藏按钮 - 不起作用:
scrollFunction() {
if (document.body.scrollTop > 5 || document.documentElement.scrollTop >5) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
滚动到顶部 - 有效:
topFunction() {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0;
}
谢谢。
最佳答案
我使用这段代码,只需更改 css 以满足您的需要。
$(document).ready(function() {
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('#scroll').fadeIn();
} else {
$('#scroll').fadeOut();
}
});
$('#scroll').click(function() {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
});
#scroll {
position: fixed;
right: 10px;
bottom: 10px;
cursor: pointer;
width: 50px;
height: 50px;
background-color: #3498db;
text-indent: -9999px;
display: none;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
#scroll span {
position: absolute;
top: 50%;
left: 50%;
margin-left: -8px;
margin-top: -12px;
height: 0;
width: 0;
border: 8px solid transparent;
border-bottom-color: #ffffff
}
#scroll:hover {
background-color: #e74c3c;
opacity: 1;
filter: "alpha(opacity=100)";
-ms-filter: "alpha(opacity=100)";
}
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<!-- BackToTop Button -->
<a href="javascript:void(0);" id="scroll" title="Scroll to Top" style="display: none;">Top<span> </span></a>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
</body>
关于javascript - 向下滚动后转到首页按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51092605/