我正在學習JavaScript,因此我決定在整個過程中創建一個頁面網站。我想在頁面中實現平滑滾動,但即使代碼顯得乾淨而正確,它也不起作用。我需要幫助解決這個問題。使用JavaScript平滑滾動問題
基本上發生了什麼事情是,當我點擊導航欄中的鏈接將我拉下目標頁面時,它根本不滾動,甚至無法執行任何操作。而且,當我點擊一個鏈接後試圖正常滾動它時,滾動抖動並且不讓我繼續滾動。
我已經檢查了調試器的錯誤,並且根據調試器沒有錯誤(至少沒有語法錯誤)。
我該如何找到問題以及如何解決?
下面是JavaScript代碼:
var targetDistance = 0;
var distanceScrolled = 0;
var bodyHeight = 0;
var Ydistance = 0;
var marginY = 0;
var speed = 55;
var tempDist = 24;
function smoothScroll(el) {
targetDistance = document.getElementsByClassName(el).offsetTop; //Target distance to scroll from current element
distanceScrolled = window.pageYOffset; //Distance scrolled from current element to target element
bodyHeight = document.body.offsetHeight; //Maximum distance of the body to scroll from the current element
Ydistance = distanceScrolled + window.innerHeight; //Total distance scrolled from the current element to the bottom
var setScroll = setTimeout(function(){
smoothScroll(el);
}, 1);
//Stop Scrolling when it hits bottom of the page
if (Ydistance >=bodyHeight) {
clearTimeout(setScroll);
}
//Scroll if the distance scrolled is less than the target distance
else if(distanceScrolled < targetDistance - 24) {
var distToScroll = distanceScrolled + 24;
window.scroll(0, distToScroll);
}
//stop when the distance scrolled equals or is greater than the target distance
else {
window.scroll(0, distToScroll);
}
}
,如果你們需要的HTML5代碼,那就是:
<!doctype html>
<html lang="en">
<head>
<title>Smooth Scrolling</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<link type="text/css" rel="stylesheet" href="style.css">
</head>
<body>
<div id="allPages" class="Page1">
<div class="navBar">
<nav>
<ul>
<li><a href="#" onclick="smoothScroll('Page4'); return false;">Contacts</a></li>
<li><a href="#" onclick="smoothScroll('Page3'); return false;">Portfolio</a></li>
<li><a href="#" onclick="smoothScroll('Page2'); return false;">About Me</a></li>
<li><a href="#" onclick="smoothScroll('Page1'); return false;">Home</a></li>
</ul>
</nav>
</div>
</div>
<div id="allPages" class="Page2">
</div>
<div id="allPages" class="Page3">
</div>
<div id="allPages" class="Page4">
</div>
<script type="text/javascript" src="script.js"></script>
</body>
如果您還需要CSS代碼,在這裏它是:
*{
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: monospace;
font-size: 18px;
}
.body {
height: 100%;
}
.navBar {
margin-top: 2%;
}
.Page1 {
height: 100vh;
}
.Page1 ul {
list-style: none;
margin-right: 10%;
margin-left: 65%;
}
.Page1 ul a {
float: right;
text-decoration: none;
padding: 15px;
color: black;
font-weight: bold;
}
.Page1 ul a:hover {
background-color: #D91E18;
color: white;
}
.Page2 {
height: 100vh;
background-color: #DADFE1;
}
.Page3 {
height: 100vh;
background-color: #DADFE1;
}
.Page4 {
height: 100vh;
background-color: #DADFE1;
}
嗨,我解決了getElementByClassname問題,但它只解決了部分問題。當我點擊按鈕向下滾動時,它會無限滾動。所以,我認爲getElementByClassName不是唯一的問題。你可以請,重新打開這個問題,並幫助我解決這個問題。在此先感謝 – einacio
沒關係,我解決了其他問題 – einacio