jQuery onClick GoTo ID 或类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5966060/
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-26 20:06:33  来源:igfitidea点击:

jQuery onClick GoTo ID or Class

jqueryclassclickgoto

提问by ToddN

For some odd reason my Header gets all messed up when I click on an A tag to go to an ID. So instead is there a way to use jQuery to do this, such as a Click(), Goto ID?

出于某种奇怪的原因,当我单击 A 标签转到 ID 时,我的 Header 变得一团糟。那么有没有一种方法可以使用 jQuery 来执行此操作,例如 Click()、Goto ID?

<a href="#allreviewstop">Read Reviews (1)</a>
<div style="height:1500px;"> Really Long Stuff</div>
<div id="allreviewstop"> My Reviews go down here</div>

This is the page I'm dealing with Click Here

这是我正在处理的页面单击此处

采纳答案by Grim...

$("div").click(function() {
    window.location.hash = "#"+$(this).attr("id");
}

Is that what you're after?

那是你追求的吗?

[edit] I can't remember if you need the # or not. Try it without if it doesn't work.

[编辑] 我不记得你是否需要#。如果它不起作用,请尝试它。

回答by Rohit Suthar

Try the jquery ScrollToplugin -

试试 jquery ScrollTo插件 -

also check the demo

还检查演示

$(function(){
    $("#goTop").click(function(){
      $.scrollTo($("#nav"), { duration: 0});
    });
});

回答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 Lucas

Does this plugin helps you: jQuery ScrollTo?

这个插件对你有帮助吗:jQuery ScrollTo