In front-end development, CSS style is crucial. CSS is used to define the layout and appearance of page elements. Sometimes, we need to dynamically change CSS styles in JavaScript code. At this time, jQuery's extension method can help us easily achieve this function.
1. Introduction of jQuery
Before using jQuery, you need to introduce the jQuery library into HTML. You can download the jQuery library from the official website, or use a CDN directly. For example:
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
2. Select elements
In jQuery, use a selector to select elements on the page. The following are some commonly used selectors:
$('p') // 选择所有的<p>元素
$('#myId') // 选择id为"myId"的元素
$('.myClass') // 选择class为"myClass"的元素
$('[name="email"]') // 选择所有name属性等于"email"的元素
$('p, span') // 选择所有<p>和<span>元素
3. Change CSS style
Once elements are selected, you can use jQuery extension methods to change their CSS styles. The following are some commonly used methods:
Use the css() method to change the CSS properties of an element. For example, the following code will change the background color of all p elements:
$('p').css('background-color', 'yellow');
You can also change multiple CSS properties through objects:
$('p').css({ 'background-color': 'yellow', 'color': 'black' });
Use addClass() and removeClass() to add or remove the class of an element. For example, the following code will add the "red" class to all p elements:
$('p').addClass('red');
This class can be set in the CSS style sheet as follows:
.red { color: red; }
You can use the removeClass() method To delete this class:
$('p').removeClass('red');
The toggleClass() method can switch between the specified class and element. For example, the following code will add or remove the "active" class for the clicked button:
$('button').click(function() { $(this).toggleClass('active'); });
Using height() and width () method can set the height and width of the element. For example, the following code will set the height of all p elements to 100 pixels and the width to 200 pixels:
$('p').height(100); $('p').width(200);
These methods can also receive callback functions in order to calculate new height and width values.
The above are some common jQuery extension methods for changing CSS styles. Through selectors and these methods, we can easily dynamically change CSS styles in the page to achieve rich interactive effects and visual design.
The above is the detailed content of How to change css style with jquery. For more information, please follow other related articles on the PHP Chinese website!