如何去页面上的特定元素? [英] How to go to a specific element on page?
问题描述
在我的HTML页面上,我希望能够'进入'/'滚动到'/'关注'页面上的元素。
通常情况下,我会使用带有 href =#something
的锚标记,但我已经使用hashchange事件以及 BBQ插件来加载此页面。
那么有没有其他方法可以通过JavaScript使页面进入页面上的给定元素?
下面是我想要做的基本大纲:
function focusOnElement(element_id){
$(' #div_'+ element_id).goTo(); //需要'去'这个元素
}
< div id =div_element1>
yadda yadda
< / div>
< div id =div_element2>
等等等等
< / div>
< span onclick =focusOnElement('element1');>点击此处转至元素1< / span>
< span onclick =focusOnElement('element2');>点击此处转至元素2< / span>
插件形式的标准技术看起来像这样:
(function($){
$ .fn.goTo = function(){
$ ('html,body')。animate({
scrollTop:$(this).offset()。top +'px'
},'fast');
return this; / for chaining ...
}
})(jQuery);
然后您可以说 $('#div_element2')。goTo );
滚动到< div id =div_element2>
。选项处理和可配置性仅供读者参考。
On my HTML page, I want to be able to 'go to' / 'scroll to' / 'focus on' an element on the page.
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.
So is there any other way, via JavaScript, to have the page go to a given element on the page?
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>
The standard technique in plugin form would look something like this:
(function($) {
$.fn.goTo = function() {
$('html, body').animate({
scrollTop: $(this).offset().top + 'px'
}, 'fast');
return this; // for chaining...
}
})(jQuery);
Then you could just say $('#div_element2').goTo();
to scroll to <div id="div_element2">
. Options handling and configurability is left as an exercise for the reader.
这篇关于如何去页面上的特定元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!