使用百分比 % 滚动到顶部 .offset()
我只是为滚动页面编写了这个,它工作正常并且做了它应该做的事情..
$('#nav a').click(function(){
var sid = $(this).attr('id');
$('html,body').animate({
scrollTop: $('#'+ sid +'-content').offset().top - 200}, 1000);
return false;
});
..但我希望偏移量是按 % 而不是 px 计算的
,即,而不是
top - 200
它可能是
top - 30%
如何实现这一点的任何想法?
一如既往,我们感谢任何帮助,并提前致谢。
快速编辑:
当前的 3 个答案(谢谢)似乎每次都会成倍增加,这不是我想要的,我希望每个答案都有 30% 窗口高度的恒定间隙所以每次 #id-content 都会滚动到顶部,并与我拥有的固定定位侧边栏对齐。
我当前的代码留下了 200px 的间隙,但这会导致不同显示器/浏览器尺寸的问题,而用 % 可以解决这个问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
以下命令将始终将框放置在距顶部 60% 的位置:
The following will position the box always 60% from the top:
您可以计算 30% 的偏移量并使用它:
这是一个示例小提琴,显示了此操作的实际情况。
You could calculate 30% of the offset and use that:
Here's an example fiddle showing this in action.
我知道这已经有很多年了,OP现在很可能已经找到了解决方案,但对于任何遇到这个问题的人来说,这是我的简单解决方案。
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..
不确定你到底想要什么 30%,但你能做的就是将你想要的百分比乘以 0.3,然后从顶部减去它。
如果它是顶部偏移量本身,您需要 30%:
当然这看起来有点愚蠢,因为它相当于
$('#'+ sid +'-content').offset().top * 0.7< /code>,但您可以将其替换为您想要的任何内容。
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:
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