jQuery:css方法 动态更改标签css样式

hello,大家好,我是wanzirui32,今天我们来学习如何使用jQuery的css方法,动态更改标签css样式。
开始学习吧!

读取标签的css样式

<!DOCTYPE html>
<html>
  <head>
   <meta charset="utf-8">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script>
     $(document).ready(function(){
     
      // 为按钮按下作准备
     	$("button").click(function(){
     
      // 获取button标签 写入单击事件的处理
    		alert($("h1").css("background-color"));// 获取h1的css属性background-color
  		});
	 });
  </script>
</head>
<body>
  <h1 style="background-color:#ff0000">测试标题</h1>
  <button>返回h1的background-color属性</button>
</body>
</html>

在这段代码中,$(“h1”).css(“background-color”)是一个重点,它获取h1标签对象,并用css方法获取background-color属性的值。

设置标签的css样式

<!DOCTYPE html>
<html>
  <head>
   <meta charset="utf-8">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script>
     $(document).ready(function(){
     
      // 为按钮按下作准备
     	$("button").click(function(){
     
      // 获取button标签 写入单击事件的处理
    		$("h1").css("background-color", "#00ff00"); // 修改p的css属性background-color
  		});
	 });
  </script>
</head>
<body>
  <h1 style="background-color:#ff0000">测试标题</h1>
  <button>修改h1的background-color属性</button>
</body>
</html>

其中,$(“h1”).css(“background-color”, “#00ff00”);把h1标签的background-color设置为了绿色。

给标签设置多个css属性

<!DOCTYPE html>
<html>
  <head>
   <meta charset="utf-8">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script>
     $(document).ready(function(){
     
      // 为按钮按下作准备
     	$("button").click(function(){
     
      // 获取button标签 写入单击事件的处理
    		// 修改或添加多个css属性 都使用字典键值对的方式来写
    		$("h1").css({
     
     "background-color":"yellow","font-size":"300%"});
  		});
	 });
  </script>
</head>
<body>
  <h1 style="background-color:#ff0000">测试标题</h1>
  <button>修改h1的css属性</button>
</body>
</html>

在“$(“h1”).css({“background-color”:“yellow”,“font-size”:“300%”});”这段代码中,我们使用来字典键值对的方式添加多个css属性。


好了,今天的课程就到这里,再见!

猜你喜欢

转载自blog.csdn.net/wangzirui32/article/details/115281052