我想在我的网站上使用向下滚动效果。我有几个锚链接。用户在使用锚链接时应该平滑滚动到链接目标。
我的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:
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;
scoll效果不起作用......我的错误在哪里?有人可以帮帮我吗?
最好的问候
答案 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) {