页面加载时使用 javascript 将锚点对象居中
我想在页面加载时跳转到锚标记,并将锚对象置于窗口的中心。我使用了一个简单的函数在页面加载时转到锚点:
<body onload="goToAnchor();">
<script type="text/javascript">
function goToAnchor() {
window.location = "#center";
}
</script>
但是为了使锚点对象居中,我需要以某种方式偏移窗口的位置。对于另一个函数,我使用类似的方法来实现适当的偏移(对象的宽度是固定的1500px):
var $offset_target = (1500 - $(window).width())/2;
这成功地确保了每次我跳到锚点时,对象都在视口中居中,而不管窗口如何尺寸。
有什么想法吗?
谢谢!!
更新/答案
因此,我使用了下面的两个回复来得出这个结论:
function goToAnchor() {
document.body.scrollLeft = document.documentElement.scrollLeft =
document.getElementById('center').offsetLeft-
(Math.ceil((- 1500 + $(window).width()) / 2));
}
它可能不是最优雅的解决方案,但它可以完成工作!非常感谢您的回答!
如果有人有更好的方法来做到这一点,请告诉我们!
I want to jump to an anchor tag when my page loads AND have the anchor object centered in the window. I've used a simple function to go to the anchor when the page loads:
<body onload="goToAnchor();">
<script type="text/javascript">
function goToAnchor() {
window.location = "#center";
}
</script>
But in order for the anchor object to be centered, I need to somehow offset the location of the window. For another function, I used something like this to achieve the appropriate offset (the width of the object is a fixed 1500px):
var $offset_target = (1500 - $(window).width())/2;
This successfully ensured that each time I jumped to an anchor, the object was centered in the viewport, regardless of the window size.
Any ideas?
Thanks!!
UPDATE/ANSWER
So, I used two of the replies below to come up with this:
function goToAnchor() {
document.body.scrollLeft = document.documentElement.scrollLeft =
document.getElementById('center').offsetLeft-
(Math.ceil((- 1500 + $(window).width()) / 2));
}
It might not be the most elegant solution, but it gets the job done! Thanks so much for your answers!
If anyone has a better way to do this, please let us know!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有 jQuery:
在大多数情况下这都可以正常工作。如果
#center
位于position
而非static
的元素中,则需要额外一点来计算正确的偏移量,否则它会将按原样工作。Without jQuery:
This will work fine in most cases. If
#center
is located in an element withposition
other thanstatic
then it would need a bit extra to calculate the correct offset, but otherwise it'll work as is.我不久前为一个网站做了这个,下面的代码使用用户窗口宽度并从静态对象的宽度中减去它,除以二并水平滚动到该位置,该位置将使对象水平居中。
I did this for a website not too long ago, the code below uses the users window width and subtracts it from your static object's width, divides by two and scrolls horizontally to that location which will center the object horizontally.
您根本不需要脚本,使用 CSS:
IE 需要处于标准模式才能工作(这仅意味着使用有效的 DOCTYPE)。将两个边距设置为 auto 会使它们具有相同的值。
这是一个以 body 元素为中心的完整示例:
You don't need script at all, use CSS:
IE needs to be in standards mode for this to work (which just means using a valid DOCTYPE). Setting both margins to auto makes them have the same value.
Here's a full example that centers the body element: