滚动到锚点

时间:2011-06-20 03:10:04

标签: javascript

<a href="javascript:ScrollToElement('q1');">this question</a>.

我测试了这段代码,为什么不用呢? 锚q1存在,但为什么不滚动到它?

2 个答案:

答案 0 :(得分:3)

有本地element.scrollIntoView()功能。

也许这会有所帮助,但您需要先选择DOM元素。

如果q1是一个ID,它将是这样的:

document.getElementById('q1').scrollIntoView(true);

答案 1 :(得分:2)

如果页面上显示,则以下代码段会滚动到name'锚点。

var element = document.anchors.namedItem(name);
if (element)
    element.scrollIntoView(false);

Live example of slightly enhanced anchor navigation。请注意缺点:location.hash不再更新。

其他可能性:

location.hash = '#' + name;  // <- this simulates following the anchor link
相关问题