Javascript DOM - 将文本元素与中心对齐? [英] Javascript DOM - aligning a text element to the center?

查看:118
本文介绍了Javascript DOM - 将文本元素与中心对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本节点附加到我想要位于页面中间的div。这些元素连接到一个mainDiv,就像整个页面一样。这是我正在尝试的代码:

I have a text node attached to a div that I want to position in the middle of the page. These elements are attached to a mainDiv which is like the whole page. Here's the code I'm trying:

title = document.createElement('div');
title.appendChild(document.createTextNode("The big title!"));
title.style.color = "#F5AE20";
title.style.textAlign = "center"; //this is what I'm trying to solve my problem

mainDiv.appendChild(title); 

不幸的是,标题停留在页面的左上角;我希望它以中心为中心。
编辑 - 只是为了澄清,如果可能,我想在Javascript中这样做。

Unfortunately the title stays on the top left of the page; I want it top centered. EDIT - just to clarify, I would like to do this within Javascript if possible.

感谢任何帮助。

推荐答案

从您发布的内容,我们不能给您一个明确的答案。

Just from what you've posted, we can't give you a definitive answer.

需要考虑到您的CSS中定义的内容以及您插入的DIV的父母。

We need to take into consideration what's defined in your CSS and also the parents of the DIV you're inserting.

将左右边距设置为auto,例如,不适用于没有定义宽度的div,并且将text-align设置为center将无法按照预期对宽度进行限制的div执行。

Setting the left and right margins to auto, for instance, won't work for a div that doesn't have a defined width, and setting text-align to be center won't work as expected for a div whose width has been constrained.

这里有一些绝对有效的示例代码:

Here's some example code that definitely works, anyway:

<html>
<head>
<script type="text/javascript">
function displayResult()
{
title = document.createElement('div');
title.appendChild(document.createTextNode("The big title!"));
title.style.color = "#F5AE20";
title.style.textAlign = "center"; //this is what I'm trying to solve my problem

document.getElementById("div1").appendChild(title); 
}
</script>
</head>
<body>

<div id="div1">This is some text.</div>
<br />

<button type="button" onclick="displayResult()">Align text</button>

</body>
</html>

这篇关于Javascript DOM - 将文本元素与中心对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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