Home  >  Article  >  Web Front-end  >  Can jquery add css styles?

Can jquery add css styles?

青灯夜游
青灯夜游Original
2022-03-16 18:47:394201browse

jquery can add css style. Method: 1. Use css() to set the style attribute of the matching element. The syntax is "$(selector).css(attribute name, attribute value)"; 2. Use attr(), the syntax is "$(selector).attr("style","style code")".

Can jquery add css styles?

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.

jquery can add css styles. For example, you can use the css() method to add CSS styles, or use the attr() method to add css inline styles by setting the style attribute.

How to add css style with jquery

1. Use css()

css( ) method returns or sets one or more style properties of the matched element.

Syntax for setting css styles

$(selector).css(name,value)
Parameters Description
name Required. Specifies the name of the CSS property. This parameter can contain any CSS property, such as "color".
value

Optional. Specifies the value of a CSS property. This parameter can contain any CSS property value, such as "red".

If the empty string value is set, removes the specified attribute from the element.

Example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script src="js/jquery-1.10.2.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("button").click(function() {
					$("p").css("color", "red");
				});
			});
		</script>
	</head>

	<body>
		<p>这是一个段落</p>
		<p>这是另一个段落</p>
		<button>改变段落的颜色</button>
	</body>
</html>

Can jquery add css styles?

##2. Use attr()

attr() method sets or returns the attribute value of the selected element.

When you use the attr() method to set the style attribute of an element, you can add a css style to the element.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script src="js/jquery-1.10.2.min.js"></script>
		<script>
			$(document).ready(function() {
				$("button").click(function() {
					// $("div").attr({"style":"border: 5px solid paleturquoise;"});
					$("div").attr("style", "border: 5px solid paleturquoise;width: 200px;");
				});
			});
		</script>
	</head>
	<body>

		<div>hello</div>
		<br>
		<button>给div元素添加css样式</button>

	</body>
</html>

Can jquery add css styles?

[Recommended learning:

jQuery video tutorial, web front-end introductory video]

The above is the detailed content of Can jquery add css styles?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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