JavaScript 居中对齐
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7625212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript Center Align
提问by Cody
How can I align the entire script to center? I've never actually coded before in javascript and I just want to modify a quick bookmarklet. I've tried stuff like align=center for different components of the script but no luck. Is there something like <center>
(in html) for js?
如何将整个脚本居中对齐?我以前从未真正用 javascript 编码过,我只想修改一个快速书签。我已经为脚本的不同组件尝试了 align=center 之类的东西,但没有运气。<center>
js有没有类似(在 html 中)的东西?
Thanks
谢谢
EDIT: basically i want this to be centered on a page
编辑:基本上我希望它以页面为中心
function dEmbed(){
var iframe = document.createElement("iframe");
iframe.src = 'http://www.google.com';
iframe.style.width = w+'px';
iframe.style.height= h+'px';
iframe.style.border= "0";
iframe.style.margin= "0";
iframe.setAttribute("scrolling","no");
iframe.setAttribute("id","NAME");
document.body.insertBefore(iframe, document.body.firstChild);
}
回答by Quentin
You can't centre a script, it doesn't look like anything so there is nothing to centre.
您无法将脚本居中,它看起来不像任何东西,因此没有什么可居中的。
If the script generates some HTML, then you can to centre the generated elements. This should be done using the usual CSS techniquesapplied to the generated element.
如果脚本生成了一些 HTML,那么您可以将生成的元素居中。这应该使用应用于生成元素的常用 CSS 技术来完成。
(<center>
and the align
attribute were deprecated in 1998and shouldn't be used).
回答by Mark Kramer
I was able to achieve this by injecting the iframe into an existing div with text-align: center
.
我能够通过将 iframe 注入现有的 div 来实现这一点text-align: center
。
Here is the example: http://jsfiddle.net/MarkKramer/PYX5s/4/
回答by Ariel
Try changing:
尝试改变:
iframe.style.margin= "0";
To:
到:
iframe.style.margin= "auto";
If it doesn't work, let me know in a comment.
如果它不起作用,请在评论中告诉我。
OK, try this change instead, change:
好的,试试这个改变,改变:
var iframe = document.createElement("iframe");
to:
到:
var div = document.createElement("div");
div.style.width = w+'px';
div.style.margin= "auto";
var iframe = document.createElement("iframe");
And change:
并改变:
document.body.insertBefore(iframe, document.body.firstChild);
To:
到:
div.appendChild(iframe);
document.body.insertBefore(div, document.body.firstChild);