简体   繁体   中英

Scroll to target inside div with overflow

Hello I want to make scroll to target inside my div with option: overflow:hidden but I doesn't work good. I don't know why my scroll script behave strange. It doesn't scroll to correct target or when I click twice on one button it back to another target. What is wrong with this? Could you help me.

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

    //shows what href contains
    var target = this.hash,
    $target = $(target);
    $('.content').stop().animate({
        'scrollTop': $target.offset().top-187 //scroll to top position on href element for example #about
    }, 1000, 'swing');
});

http://jsfiddle.net/PGnZN/1/

You are using .offset() when you should be using .position() http://api.jquery.com/position/ .offset() gets the coords relative to the document where .position() gets the coords from the offset parent. It is important to have position relative on the parent so that the value can be calculated correctly. I did not touch the 187 assuming you wanted it to show it around the middle

http://api.jquery.com/offset/

$('.content').stop().animate({
    'scrollTop': $target.position().top-187 //scroll to top position on href element for example #about
}, 1000, 'swing');

CSS

.inside{
    max-width: 680px;
    position: relative;
}

please try this

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

    //shows what href contains
    var targethash = this.hash,
    $target = $(targethash);
    $('.content').stop().animate({
        'scrollTop': $target.offset().top//-187 //scroll to top position on href element for example #about
    }, 1000, 'swing');
});

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