JavaScript中怎么实现文本左对齐

JavaScript中怎么实现文本左对齐,第1张

JavaScript中怎么实现文本左对齐

方法:1、利用setAttribute(),语法“元素对象.setAttribute("style","text-align:left")”;2、利用textAlign属性,语法“元素对象.style.textAlign="left";”。

本教程 *** 作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

JavaScript中实现文本左对齐

方法1:利用setAttribute()

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<style>
			div{
				border: 2px solid red;
				text-align: right;
			}
		</style>
	</head>

	<body>
		<div id="box">一个div元素</div><br />
		<button onclick="replaceMessage()"> 让文本左对齐</a>

			<script type="text/javascript">
				function replaceMessage() {
					var div = document.getElementById("box");
					div.setAttribute("style", "text-align: left;");
				}
			</script>

	</body>
</html>

setAttribute() 方法添加指定的属性,并为其赋指定的值。如果这个指定的属性已存在,则仅设置/更改值。

方法2:利用style对象的textAlign属性

textAlign 属性用于控制元素中文本的对齐方式,当值设置为“left”则可把文本排列到左边。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<style>
			div{
				border: 2px solid red;
				text-align: right;
			}
		</style>
	</head>

	<body>
		<div id="box">一个div元素</div><br />
		<button onclick="replaceMessage()"> 让文本左对齐</a>

			<script type="text/javascript">
				function replaceMessage() {
					var div = document.getElementById("box");
					// div.setAttribute("style", "text-align: left;");
					div.style.textAlign="left";
				}
			</script>

	</body>
</html>

【相关推荐:javascript学习教程

以上就是JavaScript中怎么实现文本左对齐的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/699921.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-23
下一篇 2022-04-23

发表评论

登录后才能评论

评论列表(0条)

保存