平滑滚动div到div

Use*_*019 4 html javascript jquery

我有一个平滑的滚动与锚和它的工作完美.但是这个JS与我使用的插件冲突,所以我需要更改脚本.

我想要的不是锚,我想使用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;
  }
}
});
});
Run Code Online (Sandbox Code Playgroud)

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

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

<div id="test"></div>
Run Code Online (Sandbox Code Playgroud)

更新:

这是以下答案的代码

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);
    }
});
});
Run Code Online (Sandbox Code Playgroud)

该代码正常工作,但当div有一个指向另一个页面的链接时,代码无效.

示例html:

<div data-anchor="/testEnvironment/how-can-i-get-a-loan/#whocangetaloan"></div>
Run Code Online (Sandbox Code Playgroud)

这个html是不同页面的地方

<section id="#whocangetaloan"></section>
Run Code Online (Sandbox Code Playgroud)

Shi*_*iel 5

如果要使用div而不是链接,可以使用数据属性来提供锚信息.标记看起来像这样:

<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>
Run Code Online (Sandbox Code Playgroud)

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

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);
    }
});
});
Run Code Online (Sandbox Code Playgroud)

演示

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