我有一個關於我的平滑滾動函數的問題,當我嘗試在HTML中使用參數調用它時,參數「不註冊」,我的參數變量獲取空值。Javascript:參數設置爲空即使給出了值
function yPosition() {
if (self.pageYOffset) return self.pageYOffset;
if (document.body.scrollTop) return document.body.scrollTop;
return 0;
}
function elementYPosition(eID) {
var element = document.getElementById(eID);
var y = element.offsetTop;
var node = element;
while (node.offsetParent && node.offsetParent != document.body) {
node = node.offsetParent;
y += node.offsetTop;
} return y;
}
function scroll(eID) {
var startY = yPosition();
var stopY = elementYPosition (eID);
var distance = stopY > startY ? stopY - startY : startY - stopY;
if (distance < 100) {
scrollTo(0, stopY);
return;
}
var speed = Math.round(distance/100);
if (speed >= 20) speed = 20;
var step = Math.round(distance/25);
var leapY = stopY > startY ? startY + step : startY - step;
var timer = 0;
if (stopY > startY) {
for (var i = startY; i < stopY; i += step) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step;
if (leapY > stopY) {
leapY = stopY;
timer++;
}
}
return;
}
for (var i = startY; i > stopY; i-= step) {
setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
leapY -= step;
if (leapY < stopY) {
leapY = stopY;
timer++;
}
}
}
相關的html:
<div id="scroll">
<a href="#problemScroll" onclick="scroll('abc'); return false"><img src="graphics/down_arrow.png" alt="down arrow" /></a>
</div>
控制檯運行時:
Uncaught TypeError: Cannot read property 'offsetTop' of
null elementYPosition js.js:12
@ js.js:12scroll
@ js.js:22onclick
@ index.html:17
我有一個以abc作爲名字的錨,這個名字來自原來的跳轉滾動,我完全忽略了它當然必須是ID的事實。該功能現在沒有錯誤,但不能按預期工作。我將發佈一篇描述發生問題的新帖子,因爲它與此完全不同。謝謝。 – haakl