jQuery jQuery从按钮onclick跳转或滚动到页面上的某个位置、div或目标

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

jQuery jump or scroll to certain position, div or target on the page from button onclick

javascriptjqueryhtmlcssscroll

提问by John

When I click on a button i want to be able to jump down or scroll to a specific div or target on the page.

当我点击一个按钮时,我希望能够向下跳或滚动到页面上的特定 div 或目标。

$('#clickMe').click(function() {
    //jump to certain position or div or #target on the page
});

How can I do this?

我怎样才能做到这一点?

回答by Joonas

I would style a link to look like a button, because that way there is a no-js fallback.

我会将链接的样式设置为看起来像一个按钮,因为这样就没有 js 回退。



So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.

所以这就是您可以使用 jquery 为跳转设置动画的方式。No-js fallback 是没有动画的正常跳转。

Original example:

原始示例:

jsfiddle

jsfiddle

$(document).ready(function() {
  $(".jumper").on("click", function( e ) {

    e.preventDefault();

    $("body, html").animate({ 
      scrollTop: $( $(this).attr('href') ).offset().top 
    }, 600);

  });
});
#long {
  height: 500px;
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Links that trigger the jumping -->
<a class="jumper" href="#pliip">Pliip</a>
<a class="jumper" href="#ploop">Ploop</a>
<div id="long">...</div>
<!-- Landing elements -->
<div id="pliip">pliip</div>
<div id="ploop">ploop</div>



New examplewith actual button styles for the links, just to prove a point.

链接的实际按钮样式的新示例,只是为了证明一点。

Everything is essentially the same, except that I changed the class .jumperto .buttonand I added css styling to make the links look like buttons.

一切都基本相同,除了我将类更改.jumper.button并添加了 css 样式以使链接看起来像按钮。

Button styles example

Button styles example

回答by Muhammad Talha Akbar

$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used