平滑滚动到特定的Div

时间:2017-01-20 05:19:16

标签: javascript jquery

我有一个链接,并试图使其顺利滚动,它的工作原理,但它使所有链接活跃我只是希望它为这个特定的链接没有其他人

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

3 个答案:

答案 0 :(得分:2)

然后在jQuery选择器中更具体 变化:

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

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

有关:

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

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

答案 1 :(得分:1)

更改

acoustic_diversity

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

并将其设为 HTML

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

答案 2 :(得分:1)

使用id选择器,而不是使用标签选择器,如下所示:

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

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


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