简体   繁体   中英

Links in page don't work

I have problem with link in one page. It work when i want scroll down, but when i want scroll up it stay in the same place. This is part of code:

(function($){
/* Store the original positions */
var d1 = $('.one');
var d1orgtop = d1.position().top;
var d2 = $('.two');
var d2orgtop = d2.position().top;
var d3 = $('.three');
var d3orgtop = d3.position().top;
var d4 = $('.four');
var d4orgtop = d4.position().top;

/* respond to the scroll event */
$(window).scroll(function(){
    /* get the current scroll position */
    var st = $(window).scrollTop();

    /* change classes based on section positions */
    if (st >= d1orgtop) {
        d1.addClass('latched');
    } else {
        d1.removeClass('latched');
    }
    if (st >= d2orgtop) {
        d2.addClass('latched');
    } else {
        d2.removeClass('latched');
    }
    if (st >= d3orgtop) {
        d3.addClass('latched');
    } else {
        d3.removeClass('latched');
    }
    if (st >= d4orgtop) {
        d4.addClass('latched');
    } else {
        d4.removeClass('latched');
    }
});

And example in JSFIDDLE JSFIDDLE

When i click href on top of the page it scroll down. But when i click href on the bottom, nothing happens. Where is my fault?

DEMO

Because of your style position:fixed on .latched class. You remove it you fix it but yea it effects the original functionality as per my visualization. so as an alternative, I have below jquery hack which actually functions as required.

$('a[href="#intro"]').on('click',function(){
  $(d1,d2,d3,d4).removeClass('latched');  
  //on click of #intro element you just remove latched class from all the elements
})

I'd a similar issue, and for some other reasons I used a function to set scroll to page.

I've tested with your example and worked fine, see the fiddle: https://jsfiddle.net/nft4oeab/3/

The function is:

function scrollToAnchor(aid){
    var aTag = $("a[name='"+ aid +"']");
    $('html,body').animate({scrollTop: aTag.offset().top},'slow');
}

Hope it helps.

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