Home > Article > Web Front-end > jquery click add delete style
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>
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; }
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(){ //代码将在此处添加 }); });
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'); }); });
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!