Home > Web Front-end > Front-end Q&A > Explore how to use JavaScript to change CSS styles

Explore how to use JavaScript to change CSS styles

PHPz
Release: 2023-04-24 10:32:15
Original
496 people have browsed it

CSS (Cascading Style Sheets) is a technology we often use in web design. It can change the appearance and layout of web pages, and make web pages more beautiful and easier to read. In this article, we will explore how to change CSS styles using JavaScript.

First, define a style sheet in HTML. The following is a simple example:

<style>
  .red {
    color: red;
  }
  .blue {
    color: blue;
  }
</style>

<div id="box">Hello World!</div>
<button id="redBtn">变成红色</button>
<button id="blueBtn">变成蓝色</button>
Copy after login

In this example, we define two CSS style classes "red" and "blue", and set the text colors to red and blue respectively.

Then, in JavaScript, we can use the document.querySelector() method to obtain DOM elements and use the .style attribute to change the CSS style. The following is an example:

const box = document.querySelector('#box');
const redBtn = document.querySelector('#redBtn');
const blueBtn = document.querySelector('#blueBtn');

redBtn.onclick = () => {
  box.style.color = 'red';
};

blueBtn.onclick = () => {
  box.style.color = 'blue';
};
Copy after login

In this example, we created three variables, corresponding to the

element and two
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template