Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

javascript - 如何转到页面上的特定元素? [重复](How to go to a specific element on page? [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

On my HTML page, I want to be able to 'go to' / 'scroll to' / 'focus on' an element on the page.

(在我的HTML页面上,我希望能够“转到”/“滚动到”/“关注”页面上的元素。)

Normally, I'd use an anchor tag with a href="#something" , but I'm already using the hashchange event along with the BBQ plugin to load this page.

(通常情况下,我会使用带有href="#something"的锚标记,但我已经使用hashchange事件和BBQ插件来加载此页面。)

So is there any other way, via JavaScript, to have the page go to a given element on the page?

(那么有没有其他方法,通过JavaScript,让页面转到页面上的给定元素?)

Here's the basic outline of what I'm trying to do:

(这是我正在尝试做的基本概述:)

function focusOnElement(element_id) {
     $('#div_' + element_id).goTo(); // need to 'go to' this element
}

<div id="div_element1">
   yadda yadda 
</div>
<div id="div_element2">
   blah blah
</div>

<span onclick="focusOnElement('element1');">Click here to go to element 1</span>
<span onclick="focusOnElement('element2');">Click here to go to element 2</span>
  ask by Cuga translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If the element is currently not visible on the page, you can use the native scrollIntoView() method.

(如果该元素当前在页面上不可见,则可以使用本机scrollIntoView()方法。)

$('#div_' + element_id)[0].scrollIntoView( true );

Where true means align to the top of the page, and false is align to bottom.

(true表示与页面顶部对齐, false表示与底部对齐。)

Otherwise, there's a scrollTo() plugin for jQuery you can use.

(否则,你可以使用jQuery scrollTo()插件 。)

Or maybe just get the top position() (docs)of the element, and set the scrollTop() (docs)--> to that position: (或者只是获取元素的top position() (docs)--> ,并将scrollTop() (docs)-->设置为该位置:)

var top = $('#div_' + element_id).position().top;
$(window).scrollTop( top );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...