开发者

Scrolling to an anchor

<a href="javascript:Scroll开发者_如何转开发ToElement('q1');">this question</a>.

I tested this code, why doesn't it work?

anchor q1 exists, but why won't it scroll to it?


There's the native element.scrollIntoView() function.

Perhaps that'll help, but you need to select the DOM element first.

If q1 was an ID, it would go like this:

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


The following code snippet scrolls to name'd anchor if present on the page.

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

Live example of slightly enhanced anchor navigation. Note the drawback: location.hash no longer updated.

Other possibility:

location.hash = '#' + name;  // <- this simulates following the anchor link
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜