Home  >  Article  >  Web Front-end  >  How to set the css style of elements in js

How to set the css style of elements in js

青灯夜游
青灯夜游Original
2021-04-29 17:38:345076browse

Setting method: 1. Use the "object.setAttribute('style', 'property: value')" statement; 2. Use the "object.style.setProperty('property', 'value')" statement ;3. Use the "Object.style.cssText='Property:Value'" statement.

How to set the css style of elements in js

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

Method 1: Use setAttribute()

<p id="p">hello world<p>

<button onclick="myFunction()">点击按钮,设置css样式</button>

<script>
function myFunction() {
	document.getElementById("p").setAttribute(&#39;style&#39;, &#39;color:#FF0000&#39;);
}
</script>

Rendering:

How to set the css style of elements in js

Method 2: Use setProperty()

<p id="p">hello world<p>

<button onclick="myFunction()">点击按钮,设置css样式</button>

<script>
function myFunction() {
	document.getElementById("p").style.setProperty(&#39;font-size&#39;, &#39;50px&#39;);
}
</script>

Rendering:

How to set the css style of elements in js

##Method 3: cssText attribute

<p id="p">hello world<p>

<button onclick="myFunction()">点击按钮,设置css样式</button>

<script>
function myFunction() {
	document.getElementById("p").style.cssText=&#39;font-size:50px;color: red;&#39;;
}
</script>

Rendering:


How to set the css style of elements in js##[Recommended learning:

javascript advanced tutorial

]

The above is the detailed content of How to set the css style of elements in js. 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