繁体   English   中英

平滑滚动div到div

[英]Smooth scroll div to div

我有一个平滑的滚动与锚和它的工作完美。 但是这个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;
  }
}
});
});

我需要的示例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而不是链接,可以使用数据属性来提供锚信息。 标记看起来像这样:

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

演示

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM