简体   繁体   中英

JavaScript doesn't scroll at second click

I have this part of code

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script>
    $(document).ready(function () {
        $("#Button1").click(function () {
            $('html, body').animate({
                scrollTop: $("#Div1").offset().top
            }, 2000);
        });
        $("#Button2").click(function () {
            $('html, body').animate({
                scrollTop: $("#Div2").offset().top
            }, 2000);
        });
        $("#Button3").click(function () {
            $('html, body').animate({
                scrollTop: $("#Div3").offset().top
            }, 2000);
        });
    });
</script>

When I get to the page, and click one of the buttons works fine, but when I need to click again it don't work.

Any idea?

It must have something to do with your HTML. I put your code in the snippet below and it works.

 $(document).ready(function () { $("#Button1").click(function () { $('html, body').animate({ scrollTop: $("#Div1").offset().top }, 2000); }); $("#Button2").click(function () { $('html, body').animate({ scrollTop: $("#Div2").offset().top }, 2000); }); $("#Button3").click(function () { $('html, body').animate({ scrollTop: $("#Div3").offset().top }, 2000); }); });
 .space { height: 100px; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id="Button1">Button1</button> <button id="Button2">Button2</button> <button id="Button3">Button3</button> <div class="space"></div> <div id="Div1">Div1</div> <div class="space"></div> <div id="Div2">Div2</div> <div class="space"></div> <div id="Div3">Div3</div> <div class="space"></div> <div class="space"></div> <div class="space"></div>

It looks okay from my end, I've created this jsfiddle for you.

I believe, the button is not working because you might be already at the same place you want to scroll to.

jsfiddle

Code Snippet

 $(document).ready(function() { $("#Button1").click(function() { $('html, body').animate({ scrollTop: $("#Div1").offset().top }, 2000); }); $("#Button2").click(function() { $('html, body').animate({ scrollTop: $("#Div2").offset().top }, 2000); }); $("#Button3").click(function() { $('html, body').animate({ scrollTop: $("#Div3").offset().top }, 2000); }); });
 .container { height: 1000px; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div id="Div1">1</div> <div id="Div2">2</div> <div id="Div3">3</div> <div class="container"> </div> <div id="Button1">click1</div> <div id="Button2">click2</div> <div id="Button3">click3</div> </body>

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