jquery click add delete style

WBOY
Release: 2023-05-12 10:32:36
Original
779 people have browsed it

jquery is an efficient and commonly used JavaScript library. It is mainly used to simplify the traversal and operation of HTML documents, event processing, and the implementation of animation effects. Front-end developers often use it to develop highly interactive web pages. Adding and deleting styles in jQuery is also a common task. Here we will introduce how to use jQuery to add and delete styles with one click.

First, we need to create a simple style list using HTML and CSS. In HTML, we can use ul and li tags to create a simple unordered list, the code is as follows:

<ul class="myList">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>
Copy after login

Next, in CSS, we can specify styles for the list items so that when adding and removing styles use. The code is as follows:

.myList li{
  padding:10px;
  border:1px solid black;
  cursor:pointer;
}
.myList li.selected{
  background-color:gray;
  color:white;
}
Copy after login

Now, in the JavaScript file, we can use jQuery to add and remove styles. First, we need to use the jQuery selector to find all the list items and add click events to them using the click() function. The code is as follows:

$(document).ready(function(){
  $('.myList li').click(function(){
    //代码将在此处添加
  });
});
Copy after login

In the click event, we can use the toggleClass() function to Add or remove the .selected class, a style already defined in CSS. The code is as follows:

$(document).ready(function(){
  $('.myList li').click(function(){
    $(this).toggleClass('selected');
  });
});
Copy after login

Now, when the list items are clicked, they will toggle the style of the selected state. If it is already selected, deselect it and vice versa. This example can be adopted online: https://codepen.io/alenaofficial/pen/zYGOYap

Adding and removing styles is that simple, and using jQuery, we can easily implement dynamic style changes to improve user experience.

The above is the detailed content of jquery click add delete style. 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