简体   繁体   中英

JQuery scroll to anchor acting odd

So i've got a script to scroll to an anchor on click. It doesnt seem to work on the "first" click going down. it will jump, rather than scroll. but after the first click, it jumps to the anchor and my menu appears, and then all the links (including the first one that jumped) work fine. im not sure what would cause this, and was wondering if anyone else would have an idea?

I have a JSFiddle, but it works fine there. only when i implement the same code into my site is when it happens.

Thanks

http://spo.comxa.com/

uploaded the files above for testing, same thing is happening.

http://jsfiddle.net/reeceheslop/b59fn43e/

$(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;

    });
});

Your click function seems to be nested inside of a scroll event listener, so I assume its not being called until something is scrolled. Try moving it to the outside along with the document ready function like this:

document.addEventListener('scroll', function (e) {
    var newPos = (window.scrollY * -1) / 5
    document.getElementById("header").style.backgroundPosition = "center " + newPos + "px";

var startY = 300;

$(window).scroll(function(){
    checkY();
});

function checkY(){
    if( $(window).scrollTop() > startY ){
        $('.fixednav').slideDown();
    }else{
        $('.fixednav').slideUp();
    }
}


checkY();

});

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