我的向下滚动效果有什么问题?

时间:2016-06-14 13:53:22

标签: javascript html drop-down-menu scroll

我想在我的网站上使用向下滚动效果。我有几个锚链接。用户在使用锚链接时应该平滑滚动到链接目标。

我的HTML代码看起来像这样(与锚点链接):

<li class="indent1">
     <a href="#eigenschaften-dartscheibe" 
        onclick="test('eigenschaften-dartscheibe'); return false;">
             Welche Eigenschaften einer Dartscheibe sind entscheidend
     </a>
</li>

链接所针对的内容部分:

<h2 id="eigenschaften-dartscheibe" class="curtain">
   Welche Eigenschaften einer Dartscheibe sind entscheidend?
</h2>

和我的Javascript:

&#13;
&#13;
function scrollTo(to, duration) {
    if (document.body.scrollTop == to) return;
    var diff = to - document.body.scrollTop;
    var scrollStep = Math.PI / (duration / 10);
    var count = 0, currPos;
    start = element.scrollTop;
    scrollInterval = setInterval(function(){
        if (document.body.scrollTop != to) {
            count = count + 1;
            currPos = start + diff * (0.5 - 0.5 * Math.cos(count * scrollStep));
            document.body.scrollTop = currPos;
        }
        else { clearInterval(scrollInterval); }
    },10);
}

function test(elID)
{
    var dest = document.getElementById(elID);
    scrollTo(dest.offsetTop, 500);
}
&#13;
&#13;
&#13;

scoll效果不起作用......我的错误在哪里?有人可以帮帮我吗?

最好的问候

1 个答案:

答案 0 :(得分:0)

您在未定义时尝试访问element。使用开发人员工具 - &gt;控制台(F12或右键单击 - &gt;在Chrome上检查)。

将元素从test传递到scrollTo

function test(elID)
{
    var dest = document.getElementById(elID);
    // Here (dest)
    scrollTo(dest, dest.offsetTop, 500);
}

然后用它来检查滚动完成的时间:

if ((document.body.scrollTop + window.innerHeight - element.offsetHeight) < to) {
  1. 计算滚动
  2. 添加窗口高度
  3. 减去元素高度以确保到达底部
  4. 小提琴:https://jsfiddle.net/xdmfpjm2/