Home  >  Article  >  Web Front-end  >  Explore how to use JavaScript to change CSS styles

Explore how to use JavaScript to change CSS styles

PHPz
PHPzOriginal
2023-04-24 09:11:38469browse

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>

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';
};

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

element and two