DOM样式的textAlign属性与CSS中的text-align属性非常相似,它为block元素的内部内容设置对齐方式。唯一的区别是,就像其他任何HTML DOM属性一样,我们可以使用JavaScript以编程方式对其进行处理。
用法
我们可以通过两种不同的方式使用textAlign,一种设置对齐方式,另一种获取当前对齐方式。
从当前DOM对象获取值。object.style.textAlign
设置当前DOM对象的值。object.style.textAlign = "left | right | center | justify |
initial | inherit";
属性值:
left:这是默认值。内容将对齐到左侧。
right:内容对齐到右侧。
center:这将内容设置为左右边之间的中心。
justify:这会在单词之间引入额外的空格,以使该行的第一个单词与左侧对齐,最后一个单词与右侧对齐。
inherit:它不会做任何花哨的事情,而是将值设置为其直接父级的值完全相同。
例:
HTML | DOM Style textAlign Property
#box-element {
border:1px solid #ff8888;
background-color:#ffaaaa;
}
.screen-center {
margin:30px auto;
width:400px;
}
#controls {
text-align:center;
}
#inside-content {
font-size:0.8rem;
}
An operating system acts as an intermediary
between the user of a computer and computer
hardware. The purpose of an operating system
is to provide an environment in which a user
can execute programs in a convenient and
efficient manner. An operating system is
software that manages the computer hardware.
The hardware must provide appropriate mechanisms
to ensure the correct operation of the computer
system and to prevent user programs from
interfering with the proper operation of
the system.
Set Alignment:
Left
Right
Center
Justify
Set Align Property
// Collecting elements
let inside_content = document.getElementById(
"inside-content");
let align_option = document.getElementById(
"alignment");
let align_btn = document.getElementById(
"do-align");
// Adding an event to the button
align_btn.onclick = function() {
// Get current value from the dropdown
let align_val =
align_option.options[align_option.selectedIndex].value;
// Set this value to alignment of the content
inside_content.style.textAlign = align_val;
}
输出:
设置alingn属性之前:
设置alingn属性后:
支持的浏览器:HTML | DOM样式textAlign属性在下面列出:
谷歌浏览器
IE浏览器
火狐浏览器
Opera
Safari