JavaScript 如何将文本内容居中对齐
在本文中,我们将使用JavaScript将文本内容居中对齐。我们使用HTML DOM style textAlign 属性来设置文本的对齐方式。
DOM style textAlign 属性与CSS中的text-align属性非常类似,它返回HTML页面中块级元素中文本的水平对齐方式,并允许对该对齐方式进行更改。
语法:
object.style.textAlign = "center"
上面的语法将文本对齐方式动态设置为居中。
示例: 此示例使用javascript将文本内容对齐到中心。
<!DOCTYPE html>
<html>
<head>
<title>
How to align text content into
center using JavaScript ?
</title>
</head>
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>
How to align text content into
center using JavaScript ?
</h3>
<p id="content">
GeeksforGeeks: A computer
science portal for geeks
</p>
<button onclick="myFunction();">
Set Alignment
</button>
<script type="text/javascript">
function myFunction() {
let txt = document.getElementById("content");
txt.style.textAlign = "center";
}
</script>
</body>
</html>
输出:

极客教程