javascript - 平滑滚动 div 到 div

标签 javascript jquery html

我有一个带有 anchor 的平滑滚动,它的工作非常完美。但是这个JS和我用的插件有冲突,所以我需要改脚本。

我想要的不是 anchor ,而是div。但我不知道该怎么做。

注意:有一个 href 链接到不同的页面。

这是我目前正在使用的脚本。

jQuery.noConflict();
jQuery(document).ready(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
    }, 1000);
    return false;
  }
}
});
});

我需要的示例html(我不知道html格式是否正确):

<div id="#test"></div>

<div id="test"></div>

更新:

下面是答案中的代码

jQuery.noConflict();
jQuery(document).ready(function($){
$('[data-anchor]').click(function(){
var target = $($(this).data('anchor'));
    if (target.length){
        $('html, body').animate({
            scrollTop: target.offset().top
        }, 1000);
    }
});
});

该代码可以正常工作,但是当 div 具有指向另一个页面的链接时,该代码将无法正常工作。

示例 html:

<div data-anchor="/testEnvironment/how-can-i-get-a-loan/#whocangetaloan"></div>

这个html放在不同的页面

<section id="#whocangetaloan"></section>

最佳答案

当您想要 div 而不是链接时,可以使用数据属性来提供 anchor 信息。标记看起来像这样:

<header>
  <div id="menu">
    <div data-anchor="#home">Home</div>
    <div data-anchor="#about">About</div>
    <div data-anchor="#services">Services</div>
    <div data-anchor="#projects">Projects</div>
    <div data-anchor="#contact">Contact</div>
  </div>
</header>

<section id="home"></section>
<section id="about"></section>
<section id="services"></section>
<section id="projects"></section>
<section id="contact"></section>

然后这个脚本将实现动画:

jQuery.noConflict();

jQuery(document).ready(function($) {

$('[data-anchor]').click(function() {

    var target = $($(this).data('anchor'));

    if (target.length) {

    $('html, body').animate({
    scrollTop: target.offset().top
    }, 1000);
    }
});
});

Demo

这将使 a 标签不再需要平滑地滚动到页面上的 anchor 。现在可以正常使用指向外部页面和 anchor 的链接,而不会以任何方式与原始脚本发生冲突。

关于javascript - 平滑滚动 div 到 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33093341/

相关文章:

javascript - 如果检查了输入,我需要增加变量 x 的值,然后警告总计 x

javascript - 如果不包含则隐藏另一个 div

javascript - 无法在 JavaScript 中设置 JSTL 数组值

javascript - 如何在 div.html() 方法中保留标记语言

javascript - 即使弹出窗口被阻止,热键插件也会打开新窗口?

JavaScript 显示/隐藏按钮

html - 使用 perl 和 html 的链接中的空格

javascript - 使用监听器删除 dom 元素会导致内存泄漏吗?

javascript - 如何从我的 Controller grails 调用 js 函数

javascript - 基于图像颜色的框阴影颜色?