简体   繁体   English

javascript水平居中

[英]javascript horizontal center

Im trying to use java script to center a page horizontally. 我试图使用Java脚本将页面水平居中。

So far i got this: 到目前为止,我得到了:

<body onload="scrollBy((document.body['scrollWidth'] - 0) / 2, 0)">

It kinda works, but not very good. 可以,但是效果不是很好。 I have a large width flash component that I need centered when the page loads and also after any click on the internal buttons. 我有一个大宽度的Flash组件,在页面加载时以及在单击内部按钮后也需要居中。

I was thinking of making a call from flash to a javascript that would scroll the page to an HTML anchor. 我正在考虑从Flash调用到将页面滚动到HTML锚点的JavaScript。

Something along the lines of: 类似于以下内容:

 <script type="text/javascript">
 function pageMid() {
 window.location.href="#mid"
 }
 </script>

But the anchors don't align to middle. 但是锚点不与中间对齐。

Any ideas? 有任何想法吗?

Thank you. 谢谢。

This worked: 这工作:

<script type="text/javascript">
function pageMid() {
scrollTo(1000, 0);
}
</script>

 <body onload="pageMid();">

Now I just cant figure it out on how to call this from flash catalyst... 现在我无法弄清楚如何从闪速催化剂中称呼它...

It sounds like you want to center the element vertically, not horizontally. 听起来好像您想使元素垂直居中,而不是水平居中。 If you know the size of the element you're trying to center, use CSS: 如果您知道要居中的元素的大小,请使用CSS:

<style>
#myThing {
   height: 300px;
   width: 400px;
   position:absolute;
   top:50%;
   left:50%;
   margin-top:-150px;
   margin-left:-200px;
}
</style>

<div id="myThing"></div>

This works 这有效

$(function () {
    scrollTo(($(document).width() - $(window).width()) / 2, 0);
});

Edit: 编辑:
I got 2 downvotes for this. 我为此得到了2张赞成票。 Maybe because I did not specify that this solution requires jQuery? 也许是因为我没有指定此解决方案需要jQuery?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM