Home >Web Front-end >Front-end Q&A >Examples to explain how to change the class style in jquery
jQuery is a popular JavaScript library for adding dynamic effects and interactive functionality to websites. One of the most commonly used functions is to change the CSS style of HTML elements, including changing class styles. This article will introduce how to use jQuery to change class styles, as well as some practical tips and techniques.
// 添加一个 class 样式 $(".my-element").addClass("active"); // 添加多个 class 样式 $(".my-element").addClass("active big"); // 删除一个 class 样式 $(".my-element").removeClass("active"); // 删除多个 class 样式 $(".my-element").removeClass("active big");
In the above example, we selected an HTML element named my-element
using the $() method and used addClass() and removeClass () method to add or remove class styles.
// 切换 class 样式 $(".my-element").toggleClass("active");
The above example will toggle the active
class style of the element named my-element
.
// 添加一个 class 样式,并在 1 秒后删除 setTimeout(function() { $(".my-element").addClass("active"); setTimeout(function() { $(".my-element").removeClass("active"); }, 1000); }, 1000);
In the above example, we first delayed it by 1 second using the setTimeout() method. In the delayed callback function, we added active# using the addClass() method. ## class style, and again use the setTimeout() method to delay for 1 second, and use the removeClass() method in the delayed callback function to delete the
active class style.
$(window).scroll(function() { if ($(this).scrollTop() > 100) { $(".my-element").addClass("scrolled"); } else { $(".my-element").removeClass("scrolled"); } });
scrolled class style; otherwise, use the removeClass() method to remove the class style.
In this article, we introduced how to use jQuery to change class styles, including adding, deleting, switching, delayed addition and deletion, and changing class styles based on conditions. These tips and techniques can help you better master jQuery and achieve more complex interactive functions and dynamic effects.
The above is the detailed content of Examples to explain how to change the class style in jquery. For more information, please follow other related articles on the PHP Chinese website!