jquery change button background

PHPz
Release: 2023-05-23 16:09:38
Original
903 people have browsed it

With the development of JavaScript technology, more and more websites are beginning to use JavaScript and jQuery to implement various functions. Today, I’m going to show you how to use jQuery to change the background of a button.

First, let’s take a look at the HTML code:

<button id="btn1">按钮 1</button>
<button id="btn2">按钮 2</button>
Copy after login

What we need to change is the background color of the button. Therefore, in the CSS file, we need to define the background color of the button:

button {
    background-color: #ccc;
}
Copy after login

Now, let us use jQuery to change the background color of the button. First, we need to add a click event to the button:

$("#btn1").click(function() {
    // TODO: 在这里添加代码
});

$("#btn2").click(function() {
    // TODO: 在这里添加代码
});
Copy after login

Now, when button 1 is clicked, we need to change its background color to orange; and when button 2 is clicked, we need to change its background color The background color changes to green. Let's add code to implement these functions.

$("#btn1").click(function() {
    $(this).css("background-color", "orange");
});

$("#btn2").click(function() {
    $(this).css("background-color", "green");
});
Copy after login

What does this code do?

First, we use jQuery’s click() function to capture the click event of the button. We then use $(this) to refer to the button that was clicked. Finally, we use the css() function to modify the background color of the button.

Now, run the web page and click the button, you will find that the background color of the button has been successfully modified.

The above is how to use jQuery to change the background color of the button. Of course, you can use other jQuery functions to achieve more complex button effects. If you want to know more about it, you can check out jQuery’s official documentation.

The above is the detailed content of jquery change button background. For more information, please follow other related articles on the PHP Chinese website!

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