开发者

Scrolling to an anchor

开发者 https://www.devze.com 2023-03-14 12:30 出处:网络
<a href=\"javascript:Scroll开发者_如何转开发ToElement(\'q1\');\">this question</a>.
<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

精彩评论

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

关注公众号