Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 滚动到jquery中的ID问题_Javascript_Jquery - Fatal编程技术网

Javascript 滚动到jquery中的ID问题

Javascript 滚动到jquery中的ID问题,javascript,jquery,Javascript,Jquery,我正在尝试创建平滑的滚动到IDs。当我点击一个链接时,它的ID应该是滚动到页面的顶部(在顶部的某个点上。例如:200px) 我试过这样的方法: var $root = $('html, body'); $('a[href*=#]').click(function() { var href = $.attr(this, 'href'); $root.animate({ scrollTop: (($(href).offset().top >= 2

我正在尝试创建平滑的滚动到
ID
s。当我点击一个链接时,它的ID应该是滚动到页面的顶部(在顶部的某个点上。例如:200px)

我试过这样的方法:

var $root = $('html, body');
  $('a[href*=#]').click(function() {
      var href = $.attr(this, 'href');
      $root.animate({
          scrollTop: (($(href).offset().top >= 200 ) ? $(href).offset().top : 200)
      }, 500, function () {
          window.location.hash = href;
      });
      return false;
  });
但它不工作,而且总是滚动到页面顶部。
希望有人能帮助我

我想,问题是你的
href
,目标可能找不到。也许您最好将要滚动到的元素存储在数据属性中,如下所示:

$('a[href*=#]').click(function(evt) {
    evt.preventDefault();
    var target = $(this).data('target');
    $('html, body').animate({
        scrollTop: $(target).offset().top
    }, 2000);
});
使用锚定标记,如下所示:

<a href="#" data-target="#somewhere_over_the_rainbow">Brilliant rainbow colors</a>


显然,ID为
的元素必须存在于您的DOM中的某个位置上。

$('a[href*=#]').click(function() {

 var href = $.attr(this, 'href');
 var top = $(href).offset().top;
 $('body').animate(
    {
     scrollTop: top - 200
    },
    500
 );
 return false;
});

显然,id等于锚点哈希的项必须存在。

我检查了它。但这对我不起作用。这意味着它将滚动到页面顶部请添加您的HTML代码。@ZakariaAcharki,我用我的HTML创建了一个演示-我选中了,它现在停止滚动不。现在不能滚动。简,我查过你的代码了。但它再次滚动到顶部。实际上,我需要在顶部的某个点停止滚动。我将此
scrollTop:$(目标).offset().top
更改为
scrollTop:$(目标).offset().top-100
,并使其正常工作。非常感谢。