JavaScript (JS) is a programming language used for designing interactive web pages and dynamic websites. JS can access and manipulate elements in HTML pages through DOM (Document Object Model). This article mainly introduces how to use JS to change CSS properties.
1. Get the element
Before changing the CSS properties, you need to get the element to be operated on. You can get an element by its element ID using the document.getElementById() method, or by a CSS selector using the document.querySelector() method.
As the following example:
HTML code:
<div id="myDiv">Hello World!</div>
JS code:
var myDiv = document.getElementById("myDiv");
or
var myDiv = document.querySelector("#myDiv");
These two lines of code will get the included text "Hello World!" div element.
2. Change CSS properties
There are two ways to change CSS properties: directly change the style through the style attribute, or change the style through the class attribute.
Change the style directly
You can use the style attribute of the element to change the CSS style. The following example changes the background color to red:
myDiv.style.backgroundColor = "red";
You can also change multiple ones at the same time Style:
myDiv.style.backgroundColor = "red"; myDiv.style.color = "white";
Through the class attribute
You can predefine multiple styles in the CSS file by changing the class attribute, and then change the style in JS through the class attribute of the element. In the following example, change the background color to blue:
CSS code:
.blue-background { background-color: blue; }
JS code:
myDiv.className = "blue-background";
In this way, you can change the background color of the div element to blue.
3. Event-triggered style changes
JS can also trigger style changes after the user performs certain operations. In the following example, when the mouse is hovering over the element, the text color is changed to green:
HTML code:
<div id="myDiv">Hello World!</div>
JS code:
var myDiv = document.getElementById("myDiv"); myDiv.onmouseover = function() { myDiv.style.color = "green"; }; myDiv.onmouseout = function() { myDiv.style.color = "black"; };
When the mouse is hovering over the element, the text color is changed will turn green; when the mouse is moved away, the text color will return to black.
Summary:
By using JS, you can easily modify the style of HTML elements to make the website more dynamic and interesting. Using the above method, you can flexibly use JS to change the style in website design to make the page more diverse.
The above is the detailed content of How to change css properties in js. For more information, please follow other related articles on the PHP Chinese website!