方法: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中怎么实现文本左对齐的详细内容。
