最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ScrollTop to element - 20px - Stack Overflow

programmeradmin1浏览0评论

I'm trying to make a scrollTop to my div element, but not exactly where it is. I want to go 20px before my div element. I think i can explain better showing my code for you:

HTML:

<div id="arrow-down">Click here and go to content!</div>

<div id="content">The content is here!</div>

JQuery: I already have a code that is working fine, but i want to make it diference.

$(document).ready(function() {
    $('#arrow-down').click(function() {
        $('html, body').animate({
               scrollTop: $("#content").offset().top
        }, 800);
    });
});

This code takes me to the div#content, but i want to go 20px from the top of this!

Something like that:

$(document).ready(function() {
    $('#arrow-down').click(function() {
        $('html, body').animate({
               scrollTop: $("#content" - 20px).offset().top
        }, 800);
    });
});

Well, i dont know if its look confused... I hope u guys can help me!

I'm trying to make a scrollTop to my div element, but not exactly where it is. I want to go 20px before my div element. I think i can explain better showing my code for you:

HTML:

<div id="arrow-down">Click here and go to content!</div>

<div id="content">The content is here!</div>

JQuery: I already have a code that is working fine, but i want to make it diference.

$(document).ready(function() {
    $('#arrow-down').click(function() {
        $('html, body').animate({
               scrollTop: $("#content").offset().top
        }, 800);
    });
});

This code takes me to the div#content, but i want to go 20px from the top of this!

Something like that:

$(document).ready(function() {
    $('#arrow-down').click(function() {
        $('html, body').animate({
               scrollTop: $("#content" - 20px).offset().top
        }, 800);
    });
});

Well, i dont know if its look confused... I hope u guys can help me!

Share Improve this question asked Nov 11, 2013 at 18:11 user2957967user2957967 711 gold badge2 silver badges4 bronze badges 2
  • 2 So subtract the 20 ... .top - 20 – epascarello Commented Nov 11, 2013 at 18:12
  • you dont want the selector to decrease, you want the offset().top of the element matching to the selector to decrease – john Smith Commented Nov 11, 2013 at 18:21
Add a ment  | 

2 Answers 2

Reset to default 5

You can do this:

$('html, body').animate({
     scrollTop: $("#content").offset().top - 20
}, 800);
$(document).ready(function() { 
    $('#arrow-down').click(function() {
         $('body').animate({
         scrollTop: $("#content").offset().top-20
    }, 800);
  }); 
});

try this

发布评论

评论列表(0)

  1. 暂无评论