JavaScript/Changing element styles

要更改元素的样式属性,请更改与元素的“样式”参数下的属性关联的值。 让我们继续上一节中的按钮示例:

<input type="button" id="myButton" value="I'm a button!">

假设我们希望隐藏具有显示样式属性的按钮。在 CSS 中,这将通过以下方式完成:

#myButton { display: none; }

如果按钮最初应该是可见的,但我们想稍后用 JavaScript 隐藏它,这将通过以下方式完成:

myButton = document.getElementById("myButton"); //searches for & detects input element of 'myButton' id
myButton.style.display = "none"; //hides the element

连字符样式 编辑

一些样式属性是连字符的。在这种情况下,相关的 JavaScript 属性没有连字符,但出现在连字符之后的字母大写。(这被称为“駝峰式大小寫”。)

例如,假设我们希望按钮的文本是粗体的。在 CSS 中,这将通过以下方式完成:

#myButton { font-weight: bold; }

如果按钮最初应该是正常的,但我们想稍后使用 JavaScript 使其文本变为粗体,则可以这样做:

myButton = document.getElementById("myButton"); //searches for & detects input element of 'myButton' id
myButton.style.fontWeight = "bold"; //makes the text bold