滚动函数抛出错误“Uncaught TypeError:无法读取属性'offsetTop'为null”

时间:2015-08-03 10:14:39

标签: javascript html

我的目的是通过点击链接按钮移动到另一个部门,它应该使页面滚动到达我想要的部门,但它没有发生。这个JavaScript代码有什么问题。

var scrollY = 0;
var distance = 40;
var speed = 24;
function autoScroll(element) {
    var targetY = document.getElementById(element).offsetTop;   
    alert(element);
    var currentY = window.pageYOffset;
    var bodyHeight = document.body.offsetHeight;
    var yPos = currentY + window.innerHeight;
    var animator = setTimeout('autoScroll(\' '+element+' \')', speed);
    if(yPos > bodyHeight) {
        clearTimeout(animator);
    } else {
        if(currentY < targetY - distance) {
            scrollY = currentY + distance;
            window.scroll(0, scrollY);
        } else {
            clearTimeout(animator);
        }
    } 

}

<h3 id = "main"> Main Heading </h3>
<a href = "#"  onclick = "return false;" onmousedown = "autoScroll('div1');"> Box 1 </a> <br/>
<a href = "#"  onclick = "return false;" onmousedown = "autoScroll('div2');"> Box 2 </a> <br/>
<a href = "#"  onclick = "return false;" onmousedown = "autoScroll('div3');"> Box 3 </a> <br/>
<a href = "#"  onclick = "return false;" onmousedown = "autoScroll('div4');"> Box 4 </a> <br/>
<div id = "div1" class = "content"> First Box </div>
<a href = "#"  onclick = "return false;" onmousedown = "release('main');"> Go Back to Main </a>
<div id = "div2" class = "content"> Second Box </div>
<a href = "#"  onclick = "return false;" onmousedown = "release('main');"> Go Back to Main </a>
<div id = "div3" class = "content"> Third Box </div>
<a href = "#"  onclick = "return false;" onmousedown = "release('main');"> Go Back to Main </a>
<div id = "div4" class = "content"> Fourth Box </div>
<a href = "#"  onclick = "return false;" onmousedown = "release('main');"> Go Back to Main </a>

2 个答案:

答案 0 :(得分:0)

offset()是一个函数,top是一个属性。

var targetY = document.getElementById(element).offset().top;   

这是对你主题中的问题的反应。问题不在于stackoverflow的良好实践。

答案 1 :(得分:0)

我发现这段代码运行正常。我刚刚使用trim()方法从元素中删除了空格。

function autoScroll(element) {
    var targetY = document.getElementById(element.trim()).offsetTop;   
    var currentY = window.pageYOffset;
    var bodyHeight = document.body.offsetHeight;
    var yPos = currentY + window.innerHeight;
    var animator = setTimeout('autoScroll(\' '+element+' \')', speed);