Home >Web Front-end >JS Tutorial >How to set the css style of elements in js
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.
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('style', 'color:#FF0000'); } </script>
Rendering:
Method 2: Use setProperty()
<p id="p">hello world<p> <button onclick="myFunction()">点击按钮,设置css样式</button> <script> function myFunction() { document.getElementById("p").style.setProperty('font-size', '50px'); } </script>
Rendering:
##Method 3: cssText attribute
<p id="p">hello world<p> <button onclick="myFunction()">点击按钮,设置css样式</button> <script> function myFunction() { document.getElementById("p").style.cssText='font-size:50px;color: red;'; } </script>Rendering:
##[Recommended learning:
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!