简体   繁体   中英

Smooth scroll to specific Div

I have a link and trying to make it smooth scroll, it works but it makes all links active I just want it for this specific link no others

<a href="#shelf"></a>

<div id="shelf">content</div>


$(document).ready(function () {
    // Add smooth scrolling to all links
    $("a").on('click', function (event) {

        // Make sure this.hash has a value before overriding default behavior
        if (this.hash !== "") {
            // Prevent default anchor click behavior
            event.preventDefault();

            // Store hash
            var hash = this.hash;

            // Using jQuery's animate() method to add smooth page scroll
            // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
            $('html, body').animate({
                scrollTop: $(hash).offset().top
            }, 800, function () {

                // Add hash (#) to URL when done scrolling (default click behavior)
                window.location.hash = hash;
            });
        } // End if
    });
});

Then be more specific in your jQuery selectors Change:

<a href="#shelf"></a>

And

 $("a").on('click', function (event) {

For:

<a href="#shelf" id="myspecificlink"></a>

And

 $("a#myspecificlink").on('click', function (event) {

Change

$("a").on("click", function(){ ... });

To

$("a#toshelf").on("click", function(){ ... }); 

And make this your HTML :

<a href="#shelf" id="toshelf">Click me!</a>

Instead of using tag selector, use id selector as below:

<a id="a1" href="#shelf"></a>

<div id="shelf">content</div>


$(document).ready(function ()
{      
   $("#a1").on('click', function (event)
    {
      //Your code here        
    });
});

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