Home  >  Article  >  Web Front-end  >  How to achieve left alignment of text in JavaScript

How to achieve left alignment of text in JavaScript

青灯夜游
青灯夜游Original
2022-02-08 11:32:224989browse

Method: 1. Use setAttribute(), the syntax is "element object.setAttribute("style","text-align:left")"; 2. Use the textAlign attribute, the syntax is "element object.style.textAlign" ="left";".

How to achieve left alignment of text in JavaScript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Achieve text left alignment in JavaScript

Method 1: Use 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>

How to achieve left alignment of text in JavaScript

The setAttribute() method adds the specified attribute and assigns it the specified value. If this specified property already exists, the value is only set/changed.

Method 2: Use the textAlign property of the style object

The textAlign property is used to control the alignment of the text in the element. When the value is set to "left", the text can be Arrange to the 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>

How to achieve left alignment of text in JavaScript

【Related recommendations: javascript learning tutorial

The above is the detailed content of How to achieve left alignment of text in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn