ChatGPT解决这个技术问题 Extra ChatGPT

平滑滚动到 div id jQuery

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

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

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

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

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

毫无进展。

@TheVanillaThrilla 我做了,但对于单个链接使用来说似乎太臃肿了
@StevenPHP,我已根据我的回答 stackoverflow.com/a/26129950/947687 替换了您示例中的 JavaScript 代码。它有效jsfiddle.net/8tLdq/643
可以在 Plain JS 中完成 - stackoverflow.com/a/61918221/741251
JS 和 jQuery 解决方案:stackoverflow.com/a/70536673/2993242

K
Kevin Lynch

您需要为 html, body 设置动画

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

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

@vector我有一个问题,一旦点击它我必须与jquery战斗才能向上滚动,有什么解决方案吗?
@yesitsme ...在我的情况下向上或向下
@GraySpectrum up,仅在单击后,听起来像是有延迟。
我有同样的问题,如果我有几个按钮需要滚动到不同的位置,尝试修改此代码但它不起作用。你能再举一个例子吗?
为它找到了一些“修复”。 proper element 的滚动现在已修复,但仍可通过单击相同的“滚动到”目标上下移动:var target = $(this).data("target"); $(".basics-content").animate({scrollTop: $(target).offset().top}, 1000); }); 说明:.basics-content 是模态的内部 div,它我实际上想滚动到 target 我提供元素的 id 号...
j
jarrodwhitley

如果您想覆盖页面上的标准 href-id 导航,而不更改 平滑滚动 的 HTML 标记,请使用以下命令 (example):

// 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});
});

这很好用,我可以建议一个非常小的调整 var pos = $(id).offset().top; 可以是 var pos = $id.offset().top;
非常好。如果您只想在某些链接上发生这种情况(例如您有一些要显示或隐藏的信息),只需向它们添加一个类名并将您的类名(例如滚动条)添加到匹配声明的末尾(例如 a[href ^="#"].scroller )。
如果没有 jQuery,你如何做到这一点?
A
Alexandre Mélard

这是我的 2 美分:

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>

仅当您不声明 doctype 时,此接缝才有效。
这里的 eval 有什么用?
我认为需要 $('html, body').animate 才能滚动
N
Nitin Jadhav

纯JS:

如果您使用现代浏览器,可以用纯 JS 完成。

document
    .getElementById("range-calculator")
    .scrollIntoView({ behavior: "smooth" });

浏览器支持有点问题,但modern browsers support it


iOS 上的 Safari 不支持这个
普通嫌犯。桌面上的 Safari 也不支持它(根据 MDN)
我刚刚尝试了 safari 桌面,它现在可以工作了。
我查看了几个类似的问题,这个答案(使用 ....scrollIIntoView(...))是唯一对我有用的非滚动页面,目标加载在滚动 div 中(Chrome 102.0.5005.61 (官方构建)(arm64))
E
Eugen

再举一个例子:

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>

早些时候它没有滚动到 div 的顶部,但后来我做了下面提到的更改并且它起作用了。 scrollTop: ($(target).offset().top - 120)
S
Shuvo Habib

我对 Vanilla JS 和 jQuery 的解决方案

香草JS:

document
    .querySelector("#myDiv")
    .scrollIntoView({ behavior: "smooth" });

jQuery:

您需要为 html、body 设置动画

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

CSS:

html {
  scroll-behavior: smooth;
}

scroll-behavior 的其他属性

scroll-behavior: auto|smooth|initial|inherit;

i
iDanielBH

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

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

B
Bibiano Wenceslao

这是我使用的:

<!-- 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>

这个的美妙之处在于您可以使用无限数量的哈希链接和相应的 id,而无需为每个链接执行新脚本。

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

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

如果您使用任何其他 CMS 或仅使用 HTML,则可以在结束正文标记 </body> 之前的一个部分中插入代码,该部分会加载到所有页面上。

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

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


喜欢这是多么简单和香草,完美。
M
MortalViews

你确定你正在加载 jQuery scrollTo 插件文件吗?

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

scrollTO 方法不是本机 jquery 方法。要使用它,您需要包含 jquery 滚动到插件文件。

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

解决方案:将其添加到头部。

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

这应该是公认的答案。问题中的代码是正确的,并且工作正常。看起来好像 scrollTo 插件没有/没有工作。 . .他没有询问做类似事情的不同方法。
R
Ramon Weijenbarg

该脚本是对 Vector 脚本的改进。我对它做了一点改动。因此,此脚本适用于其中包含 page-scroll 类的每个链接。

起初没有缓和:

$("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');
});

您可以在此处找到所有缓动:Cheat Sheet


S
Suraj Rao

这是最简单的。Source-https://www.w3schools.com/jsref/met_element_scrollintoview.asp

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

M
Mario

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

只需将“.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;
  }
}
});

J
JoyGuru

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

可从此处找到教程、演示和源代码 - Smooth scroll to div using jQuery

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:

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

S
Suraj Rao

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

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

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

HTML:

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

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

你的答案有什么不同?
Y
Y. Joy Ch. Singha

这对我有用。

<div id="demo">
        <h2>Demo</h2>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
    $(document).ready(function () {
        // Handler for .ready() called.
        $('html, body').animate({
            scrollTop: $('#demo').offset().top
        }, 'slow');
    });
</script>

谢谢。