jQuery 中的 width( )方法函数

首页 / jQuery入门教程 / jQuery 中的 width( )方法函数

width()方法获取第一个匹配元素的当前计算像素宽度。

width( ) - 语法

selector.width( )

此方法能够找到窗口和文档的宽度,如下所示:

$(window).width();   //返回浏览器窗口的宽度
$(document).width(); //返回 HTML 文档的宽度

width( ) - 示例

<html>
   <head>
      <title>The jQuery Example</title>
      <script type="text/javascript" 
         src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type="text/javascript" language="javascript">
         $(document).ready(function() {
			
            $("div").click(function () {
               var color=$(this).css("background-color");
               var width=$(this).height();
               $("#result").html("That div is <span>" +color+ "</span>.");
               $("#result").css({'color': color, 'background-color':'gray'});
               $("#result").width( width );
            });
				
         });
      </script>
		
      <style>
         div { width:60px; height:60px; margin:5px; float:left; }
      </style>
   </head>
	
   <body>
      <p>Click on any square:</p>
      <span id="result"> </span>
		
      <div style="background-color:blue; height:50px;"></div>
      <div style="background-color:pink;height:30px;"></div>
      <div style="background-color:#123456;height:100px;"></div>
      <div style="background-color:#f11; height:75px;"></div>
   </body>
</html>

这将产生以下输出-

无涯教程网

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

技术与商业案例解读 -〔徐飞〕

Service Mesh实践指南 -〔周晶〕

Linux性能优化实战 -〔倪朋飞〕

面试现场 -〔白海飞〕

编辑训练营 -〔总编室〕

性能优化高手课 -〔尉刚强〕

超级访谈:对话汤峥嵘 -〔汤峥嵘〕

快手 · 音视频技术入门课 -〔刘歧〕

Serverless进阶实战课 -〔静远〕

好记忆不如烂笔头。留下您的足迹吧 :)