简体   繁体   中英

jQuery smooth scrolling anchor problems

I'm very new to jQuery and am trying to achieve smooth scrolling to a div on my web project. For some reason, when I create a new basic html test page and add the js for the scrolling, it works. However when I import the exact same code into my main project, it doesn't actually scroll and instead jumps straight to the intended div after a slight pause. I have no idea why it would work on a test page and not in my actual project. Does anyone have any ideas as to what would be causing it to do this? Any help would be much appreciated! Thanks.

I have the following scripts defined in the head:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="js/script.js"></script>

The HTML:

<div id="mainContent">
    <section id="splash">
        <div class="banner">

        </div>

        <div id="intro">
            <h1>Heading 1</h1>
            <h2>Heading 2</h2>
            <a href="#productInfo">LEARN MORE</a>
        </div>

    </section>

    <div id="productInfo">
            </div>

and inside script.js:

$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash,
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});
});

Done it in fiddle

Below is the code,

HTML:

<section id="splash">
    <div class="banner"></div>
    <div id="mainContent">
        <div id="intro">
            <h1>Heading 1</h1>
            <h2>Heading 2</h2>
            <a href="#productInfo">LEARN MORE</a>
        </div>
    </div>
</section>
<div id="productInfo">test tests</div>

CSS:

#productInfo { background:gray; color:#000; margin-top:400px; padding:10px; height:1000px;}

jQuery:

$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash,
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;

    });
});
});

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