jquery中的attr属性

xiaoxiao2021-02-28  94

1.attr属性 首先看一例代码:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/jquery-3.0.0.js"></script> <style type="text/css"> img{ width: 300px; height: 300px; border: 5px solid #ccc; } </style> </head> <body> <img src="img/1.jpg"/> <script type="text/javascript"> $(function(){ $("img").click(function(){ //alert(1); $("img").attr("width","500"); $("img").attr("height","500"); }) }) </script> </body> </html>

读者朋友觉得上面的代码中,有问题么? 如果有的话,问题出在哪儿? 那我们试一下,看它有没有获取到img的宽度呢?

$("img").click(function(){ console.log($("img").attr("width")); $("img").attr("width","500"); $("img").attr("height","500"); })

console.log的结果是undefined 这说明了没有获取到width。

我们看一下内联的写法

<img src="img/meinv.jpg" width="300" height="300"/> <div style="width:500px;height:300px;background: #f99;"> 记得加px </div>

长时间不同内联样式,居然忘却了它的存在。 写成上面第一种这种写法就可以正常获取,原因目前正在探索中。 补充:原因已经找到 因为attr设置的是属性

<div style="width:500px;height:300px;background: #f99;"> 记得加px </div>

就像上面这个例子,属性是style,而不是width或者height或者background; 但下面这个就不一样了,

<img src="img/meinv.jpg" width="300" height="300"/>

属性时width和height。 代码如下:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="js/jquery-3.0.0.js"></script> <style type="text/css"> img{ border: 5px solid #ccc; } </style> </head> <body> <img src="img/1.jpg" width="300" height="300"/> <script type="text/javascript"> $(function(){ $("img").click(function(){ //alert(1); console.log($("img").attr("width")); $("img").attr("width","500"); $("img").attr("height","500"); }) }) </script> </body> </html>

重点在这里

<img src="img/1.jpg" width="300" height="300"/>

我们再看看这两行代码

$("img").attr("width","500"); $("img").attr("height","500");

还可以这样写:

$("img").attr({"width":"500","height":"500"});
转载请注明原文地址: https://www.6miu.com/read-75071.html

最新回复(0)