Javascript 如何让 jQuery 直接转到 <h2 id="id-name">?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5193167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:06:11  来源:igfitidea点击:

How I can I make jQuery go directly to <h2 id="id-name">?

javascriptjquery

提问by udexter

I want to make jQuery navigates directly (no animation need) to a id that I pass in a variable.

我想让 jQuery 直接导航(不需要动画)到我在变量中传递的 id。

I have various marks like id="content", id="edit", id="..."that are <h2>titles. Doing validation with PHP I will output a variable like var NAVIGATE_TO = <?php echo $where_failed;?>and I want to move the website to that idposition.

我有各种标记,例如id="content", id="edit"id="..."<h2>标题。使用 PHP 进行验证我将输出一个变量,例如var NAVIGATE_TO = <?php echo $where_failed;?>,我想将网站移动到该id位置。

Like if I do domain.tld/page#editor #contentbut with jQuery because when I load the page my PHP framework doesn't allow me to indicate the hash.

就像我使用 jQuerydomain.tld/page#edit#content使用 jQuery 一样,因为当我加载页面时,我的 PHP 框架不允许我指示哈希。

回答by Yi Jiang

You can set location.hashto the idyou need the browser to scroll to:

您可以设置location.hashid您需要浏览器滚动到:

window.location.hash = '#edit';

回答by Patrick

In my experience the window.location.hashsolution only works once. If you don't want to use the plugin you could try this:

根据我的经验,该window.location.hash解决方案仅适用一次。如果你不想使用插件,你可以试试这个:

var navigationFn = {
    goToSection: function(id) {
        $('html, body').animate({
            scrollTop: $(id).offset().top
        }, 0);
    }
}

and then call it like so (where someIDis the ID of the element you wish to scroll to):

然后像这样调用它(someID您希望滚动到的元素的 ID在哪里):

navigationFn.goToSection('#someID');

With this you can also vary the animation speed (I have it at 0) so that it is instant, but you could pass the value to the function so the code is reusable.

有了这个,您还可以改变动画速度(我将其设置为 0),以便它是即时的,但您可以将值传递给函数,以便代码可重用。

回答by Kimtho6

Use the jquery scrolltoplugin then you can do it like this

使用 jquery scrollto插件然后你可以这样做

$(document).ready(function(){  
      $(".topMenu").click(function() {
        $.scrollTo($("#edit"), { duration: 0});
      });

回答by Yusufbek

I know it's an old question, but I thought it would be also a good solution if just want the element to be visible in the browsers view. (scroll without any animation).

我知道这是一个老问题,但我认为如果只是希望元素在浏览器视图中可见,这也是一个很好的解决方案。(滚动没有任何动画)。

var elem = document.getElementById("yourContent");
elem.scrollIntoView();

The above sample is taken from https://www.w3schools.com/jsref/met_element_scrollintoview.asp

以上示例摘自https://www.w3schools.com/jsref/met_element_scrollintoview.asp