jquery怎么改变style样式

武飞扬头像
PHP中文网
帮助576

jquery改变style样式有两种方法:

  • 通过css()方法来修改

  • 通过attr()方法来修改

方法1:使用css()方法

css() 方法可以设置匹配的元素的一个或多个样式属性。

直接利用css() 方法设置新style样式即可

语法:

$(selector).css({"属性名1":"属性值1","属性名2":"属性值2",...})

示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="https://www.swvq.com/js/jquery-3.6.3.min.js"></script>
		<script>
			$(document).ready(function() {
				$("button").on("click", function() {
					$("div").css({"color":"red","background-color":"papayawhip","font-size":"25px"});
				});
			});
		</script>
		<style>
			.tr1 {
				color: green;
			}
			.tr2 {
				color: red;
				background-color: blanchedalmond;
			}
		</style>
	</head>

	<body class="ancestors">
		<div style="color: yellow;background-color:powderblue;">欢迎来到PHP中文网!</div><br>
		<button>改变div元素的style样式</button>
	</body>

</html>

学新通技术网

方法2:使用attr()方法

attr() 方法设置或返回被选元素的属性值。

只需要使用attr() 方法设置元素的style属性值即可。

语法:

$(selector).attr("style","属性名1:属性值1;属性名2:属性值3;...")

示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="https://www.swvq.com/js/jquery-3.6.3.min.js"></script>
		<script>
			$(document).ready(function() {
				$("button").on("click", function() {
					$("div").attr("style", "color:pink;background-color:peru;font-size: 18px;");
				});
			});
		</script>
		<style>
			.tr1 {
				color: green;
			}
			.tr2 {
				color: red;
				background-color: blanchedalmond;
			}
		</style>
	</head>

	<body class="ancestors">
		<div style="color: red;background-color:papayawhip;">欢迎来到PHP中文网!</div><br>
		<button>改变div元素的style样式</button>
	</body>

</html>

学新通技术网

本篇文章来至:IT社区

系列文章
更多 更多
同类精品
更多 更多
我要评论
我的头像
精彩评论
继续加载