scroll to top .offset() using percentage %

£可爱£侵袭症+ 提交于 2019-12-23 10:57:22

问题


I just wrote this for scrolling pages which is working fine and does what it should..

$('#nav a').click(function(){

var sid = $(this).attr('id');

$('html,body').animate({
 scrollTop: $('#'+ sid +'-content').offset().top - 200}, 1000);
  return false;
});

..but I want the offset to be calculated by % rather then px

ie rather then

top - 200 

it could be

top - 30%

any ideas how to accomplish this?

As always any help is appreciated and thanks in advance.

Quick Edit:

The current 3 answers (thank you) seem to multiply each time which is not what I want, I wish to have a constant gap of 30% window height each time so each time the #id-content is scrolled to the top lines up with a fixed positioned sidebar I have.

My current code leaves a 200px gap but that causes an issue with different monitor/browser sizes where as a % would sort it out.


回答1:


The following will position the box always 60% from the top:

var offset = parseInt($('#example').offset().top);
var bheight = $(window).height();
var percent = 0.6;
var hpercent = bheight * percent;
$('html,body').animate({scrollTop: offset - hpercent}, 1000);



回答2:


You could calculate 30% of the offset and use that:

$('#nav a').click(function(){

    var sid = $(this).attr('id');
    var offset = $('#'+ sid +'-content').offset().top;

    $('html,body').animate({scrollTop: offset - (offset * 0.3)}, 1000);
    return false;
});

Here's an example fiddle showing this in action.




回答3:


I know this is years old and the OP has most likely found a solution by now, but here's my simple solution for anyone who comes across this anyway..

  var navBarHeight = $('#navBar').height();
            $('html, body').animate({
                scrollTop: $("#scrollDestination").offset().top-navbarheight
            }, 1000);



回答4:


Not sure exactly what you want 30% of, but what you can do is just multiply what you want a percentage of by 0.3, and then subtract that from top.

If it's the top offset itself you want 30% of:

$('html,body').animate({
    scrollTop: $('#'+ sid +'-content').offset().top - $('#'+ sid +'-content').offset().top * 0.3 }, 1000);
    return false;
});

Of course that seems a bit silly, since it's just equivalent to $('#'+ sid +'-content').offset().top * 0.7, but you can replace it with whatever you want.




回答5:


Try this

$('#nav a').click(function(){

var sid = $(this).attr('id');
var contentTop = $('#'+ sid +'-content').offset().top;
contentTop = parseInt(contentTop - (contentTop *0.3)); 
$('html,body').animate({ scrollTop: contentTop }, 1000);
  return false;
});


来源:https://stackoverflow.com/questions/6736582/scroll-to-top-offset-using-percentage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!