开发者

scroll to top .offset() using percentage %

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 constan开发者_开发问答t 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.


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);


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.


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);


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.


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;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜