我正在嘗試使單擊時回傳到頂部的按鈕可以平滑滾動,但我被卡住了.. 目前此代碼有效,但不能平滑滾動到頁面頂部.. 任何人都可以幫我解決這個問題?
<a id="BackToTop" href="#" title="Back to the top" class="back-to-top hide">
<span>?</span>
</a>
<style>
.back-to-top {
position: fixed;
bottom: 20px;
right: 25px;
color: #999;
background-color: #243066;
z-index: 60000;
}
.back-to-top span{
height: 47px;
}
.hide {
display: none!important;
}
.back-to-top:hover {
box-shadow: 1px 1px 25px #9e9e9e;
}
</style>
<script>
(function() {
function trackScroll() {
var scrolled = window.pageYOffset;
var coords = 300;
if (scrolled > coords) {
goTopBtn.classList.remove('hide');
}
if (scrolled < coords) {
goTopBtn.classList.add('hide');
}
}
function backToTop() {
if (window.pageYOffset > 0) {
window.scrollBy(0, -80);
setTimeout(backToTop, 0);
}
}
var goTopBtn = document.querySelector('.back-to-top');
window.addEventListener('scroll', trackScroll);
goTopBtn.addEventListener('click', backToTop);
})();
</script>
uj5u.com熱心網友回復:
現代瀏覽器(除了 IE 之外的所有瀏覽器)都支持scrollTo視窗物件上的一種方法,您可以將平滑滾動行為傳遞給:
window.scrollTo({ top: 0, left: 0, behavior: 'smooth'});
這也有一些變化,例如element.scrollIntoView()
uj5u.com熱心網友回復:
你可以用那個
document.getElementById('id').scrollIntoView({
behavior: 'smooth'
});
uj5u.com熱心網友回復:
document
.getElementById("id")
.scrollIntoView({ block: "start", behavior: "smooth" });
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/460895.html
標籤:javascript html jQuery css
上一篇:IDEA通過Jedis操作Linux上的Redis;Failed to connect to any host resolved for DNS name問題
下一篇:如何獲取更改的輸入標簽的值?
