平滑滚动到 div id jQuery

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

Smooth scroll to div id jQuery

javascriptjqueryscroll

提问by StevenPHP

I've been trying to get a scroll to div id jquery code to work correctly. Based on another stack overflow question i tried the following

我一直在尝试滚动到 div id jquery 代码才能正常工作。基于另一个堆栈溢出问题,我尝试了以下操作

DEMO http://jsfiddle.net/kevinPHPkevin/8tLdq/

演示http://jsfiddle.net/kevinPHPkevin/8tLdq/

$('#myButton').click(function() {
   $.scrollTo($('#myDiv'), 1000);
});

But it didn't work. It just snaps to the div. I also tried

但它没有用。它只是捕捉到 div。我也试过

$('#myButton').click(function(event) {
     event.preventDefault();
   $.scrollTo($('#myDiv'), 1000);
});

With no progress.

毫无进展。

回答by Kevin Lynch

You need to animate the html, body

你需要动画 html, body

DEMO http://jsfiddle.net/kevinPHPkevin/8tLdq/1/

演示http://jsfiddle.net/kevinPHPkevin/8tLdq/1/

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);
});

回答by dizel3d

If you want to override standard href-id navigationon the page without changing the HTML markup for smooth scrolling, use this (example):

如果要覆盖页面上的标准href-id 导航而不更改 HTML 标记以实现平滑滚动,请使用此(示例):

// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
    // target element id
    var id = $(this).attr('href');

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

    // top position relative to the document
    var pos = $id.offset().top;

    // animated top scrolling
    $('body, html').animate({scrollTop: pos});
});

回答by Alexandre Mélard

here is my 2 cents:

这是我的 2 美分:

Javascript:

Javascript:

$('.scroll').click(function() {
    $('body').animate({
        scrollTop: eval($('#' + $(this).attr('target')).offset().top - 70)
    }, 1000);
});

Html:

网址:

<a class="scroll" target="contact">Contact</a>

and the target:

和目标:

<h2 id="contact">Contact</h2>

回答by Bibiano Wenceslao

Here's what I use:

这是我使用的:

<!-- jquery smooth scroll to id's -->   
<script>
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 500);
        return false;
      }
    }
  });
});
</script>

The beauty with this one is you can use an unlimited number of hash-links and corresponding ids without having to execute a new script for each.

这样做的好处是您可以使用无限数量的哈希链接和相应的 ID,而无需为每个链接执行新脚本。

If you're using WordPress, insert the code in your theme's footer.phpfile right before the closing body tag </body>.

如果您使用 WordPress,请将代码插入主题footer.php文件中的结束正文标记之前</body>

If you have no access to the theme files, you can embed the code right inside the post/page editor (you must be editing the post in Text mode) or on a Text widget that will load up on all pages.

如果您无法访问主题文件,您可以将代码嵌入到帖子/页面编辑器中(您必须在文本模式下编辑帖子)或将在所有页面上加载的文本小部件。

If you're using any other CMS or just HTML, you can insert the code in a section that loads up on all pages right before the closing body tag </body>.

如果您正在使用任何其他 CMS 或仅使用 HTML,您可以将代码插入到所有页面都在关闭正文标记之前加载的部分中</body>

If you need more details on this, check out my quick post here: jQuery smooth scroll to id

如果您需要更多详细信息,请在此处查看我的快速帖子:jQuery smooth scroll to id

Hope that helps, and let me know if you have questions about it.

希望对您有所帮助,如果您对此有任何疑问,请告诉我。

回答by Eugen

one example more:

再举一个例子:

HTML link:

HTML链接:

<a href="#featured" class="scrollTo">Learn More</a>

JS:

JS:

  $(".scrollTo").on('click', function(e) {
     e.preventDefault();
     var target = $(this).attr('href');
     $('html, body').animate({
       scrollTop: ($(target).offset().top)
     }, 2000);
  });

HTML anchor:

HTML 锚点:

  <div id="featured">My content here</div>

回答by iDanielBH

This code will be useful for any internal link on the web

此代码对于网络上的任何内部链接都很有用

    $("[href^='#']").click(function() {
        id=$(this).attr("href")
        $('html, body').animate({
            scrollTop: $(id).offset().top
        }, 2000);
    });

回答by Ramon Weijenbarg

This script is a improvement of the script from Vector. I have made a little change to it. So this script works for every link with the class page-scroll in it.

该脚本是对 Vector 脚本的改进。我对它做了一点改动。所以这个脚本适用于每个包含类页面滚动的链接。

At first without easing:

起初没有缓和:

$("a.page-scroll").click(function() {
    var targetDiv = $(this).attr('href');
    $('html, body').animate({
        scrollTop: $(targetDiv).offset().top
    }, 1000);
});

For easing you will need Jquery UI:

为方便起见,您将需要 Jquery UI:

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

Add this to the script:

将此添加到脚本中:

'easeOutExpo'

Final

最终的

$("a.page-scroll").click(function() {
    var targetDiv = $(this).attr('href');
    $('html, body').animate({
        scrollTop: $(targetDiv).offset().top
    }, 1000, 'easeOutExpo');
});

All the easings you can find here: Cheat Sheet.

您可以在此处找到所有缓动:备忘单

回答by MortalViews

are you sure you are loading the jQuery scrollTo Plugin file?

您确定要加载 jQuery scrollTo 插件文件吗?

you might be getting a object: method not found "scrollTo" error in the console.

您可能会在控制台中收到一个对象:方法未找到“scrollTo”错误。

the scrollTO method is not a native jquery method. to use it you need to include the jquery scroll To plugin file.

scrollTO 方法不是原生 jquery 方法。要使用它,您需要包含 jquery scroll To 插件文件。

ref: http://flesler.blogspot.in/2009/05/jqueryscrollto-142-released.htmlhttp://flesler.blogspot.in/2007/10/jqueryscrollto.html

参考:http: //flesler.blogspot.in/2009/05/jqueryscrollto-142-released.html http://flesler.blogspot.in/2007/10/jqueryscrollto.html

soln: add this in the head section.

soln:在 head 部分添加这个。

<script src="\path\to\the\jquery.scrollTo.js file"></script>

回答by JoyGuru

You can do it by using the following simple jQuery code.

您可以使用以下简单的 jQuery 代码来实现。

Tutorial, Demo, and Source code can be found from here - Smooth scroll to div using jQuery

可以从这里找到教程、演示和源代码 -使用 jQuery 平滑滚动到 div

JavaScript:

JavaScript:

$(function() {
    $('a[href*=#]:not([href=#])').click(function() {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
        if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    });
});

HTML:

HTML:

<a href="#section1">Go Section 1</a>
<div id="section1">
    <!-- Content goes here -->
</div>

回答by waqas noor

Here I tried this, that work great for me.

我在这里尝试了这个,这对我很有用。

$('a[href*="#"]').on('click', function (e) {
    e.preventDefault();

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

HTML:

HTML:

 <a href="#fast-food" class="active" data-toggle="tab" >FAST FOOD</a>

<div id="fast-food">
<p> Scroll Here... </p>
  </div>