简体   繁体   中英

Smooth scroll div to div

I have a smooth scroll with the anchor and its work perfectly. But this JS is conflict to the plugin that I use, so I need to change the script.

I want is instead of an anchor, I want to use a div. But I don't know how doing this.

Note: There's an a href where link to a different page.

Here's the script that I'm currently using.

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

Example html that I need (I don't know if the html is in correct format):

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

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

Updated:

Here's the code from answer below

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

That code is working, but when the div has a link that pointed to another page, the code is not working.

Example html:

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

This html is place to different page

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

When you want to have divs instead of links, a data attribute could be used to provide the anchor info. The markup would look something like this:

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

And this script will then implement the animation :

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

This will make a tags no longer needed to smoothly scroll to an anchor on the page. Links to an external page and anchor can now be used normally without the original script conflicting in any way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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