我一直试图得到一个滚动到div id jquery代码正确工作。基于另一个堆栈溢出问题,我尝试了以下

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

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

但这并没有起作用。我也试过了

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

毫无进展。


当前回答

再举一个例子:

HTML链接:

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

JS:

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

HTML锚:

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

其他回答

这个脚本是对Vector脚本的改进。我对它做了一点改动。因此,这个脚本适用于带有类页面的每个链接—在其中滚动。

起初不放松:

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

为了缓解你将需要Jquery UI:

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

把这个添加到脚本中:

'easeOutExpo'

最后

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

你可以在这里找到所有的便利:小抄。

以下是我的观点:

Javascript:

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

Html:

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

目标:

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

下面是我的解决方案,平滑滚动到div /锚使用jQuery,以防你有一个固定的标题,这样它就不会在它下面滚动。 同样,如果你从其他页面链接它。

只需替换”。Site-header”到包含标题的div。

$(function() {

$('a[href*="#"]:not([href="#"])').click(function() {
var headerheight = $(".site-header").outerHeight();
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 - headerheight)
    }, 1000);
    return false;
  }
}
});

//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var headerheight = $(".site-header").outerHeight();
  var target = $('#'+location.href.split("#")[1]);
  if (target.length) {
    $('html,body').animate({
      scrollTop: target.offset().top - headerheight
    }, 1);
    return false;
  }
}
});

这是一个简单的。source -https://www.w3schools.com/jsref/met_element_scrollintoview.asp

var elmnt = document.getElementById("content");
elmnt.scrollIntoView();

你需要动画html,主体

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

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