滚动到顶部.offset()使用百分比% [英] scroll to top .offset() using percentage %

查看:281
本文介绍了滚动到顶部.offset()使用百分比%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是为了滚动页面而写的,它可以正常工作并完成应有的工作.

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

..但是我希望偏移量由%计算,而不是px

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

即是

top - 200 

可能是

top - 30%

有什么想法可以做到这一点吗?

any ideas how to accomplish this?

一如既往,感谢您的帮助.

As always any help is appreciated and thanks in advance.

快速

Quick

当前的3个答案(谢谢)似乎每次都在增加,这不是我想要的,我希望每次都有30%的窗口高度恒定的间隙,因此每次#id-content滚动到顶部与固定的侧边栏对齐.

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.

我当前的代码留有200像素的间隙,但是这导致了监视器/浏览器大小不同的问题,以%的百分比可以解决该问题.

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

推荐答案

以下内容将使框始终位于顶部的60%处:

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

这篇关于滚动到顶部.offset()使用百分比%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆