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
精彩评论