2009-11-25 116 views
0

我有一个第三方脚本是设置图像的宽度和高度,但对于我的生活,我无法弄清楚它是如何做到这一点。它可能来自数据库或者一个类,但是它们有很多。如何使用jQuery更改属性?

的HTML看起来是这样的:

<img src="..." width="30px" height="30px"> 

使用jQuery,我怎么可以改变高度和宽度值?

我猜它是这样的:

$("..[$width="]").replace(

这里是元素的HTML:

<div id="prodThumbnails"> 
<table style="width: 641px;"> 
<tbody> 
<tr> 
<td align="right" style="vertical-align: middle;">   
</td> 
<td nowrap="nowrap" class="productPhotoThumbnailSection"> 
<a onclick="javascript:drawMainImage('0', '')" href="javascript:swapImage()"> 
<img height="30" width="30" border="0" title="" alt="" 
src="images/products/85.png"/></a> 
      
<a onclick="javascript:drawMainImage('1', '')" href="javascript:swapImage()"><img height="30" width="30" border="0" title="" alt="" 
src="images/products/90.jpg"/></a> 
      
<a onclick="javascript:drawMainImage('2', '')" href="javascript:swapImage()"> 
<img height="30" width="30" border="0" title="" alt="" src="images/products/92.jpg"/></a> 
</td> 
<td align="left" style="vertical-align: middle;"> 
</td> 
</tr> 
</tbody> 
</table> 
</div> 

我试着这样做:

$(function() { 
    $("td.productPhotoThumbnailSection img").attr("width","64px"); 
    $("td.productPhotoThumbnailSection img").attr("height","64px"); 

    }); 

,但会将设置图像宽度和高度为0.

回答

0

认为#attr(key,value)应该在这里工作。更多在docs

1

假设<img id="blah" ...>以上:

$('#blah').attr({ 
    width: '30px', 
    height: '30px' 
}); 
3

因此,你要设置为width一个新值,height属性的元素?你可以用attr()函数来做到这一点。

基本例如:

element.attr('width', '100'); 
element.attr('height', '100'); 

或链接:

element.attr('width', '100').attr('height', '100'); 

或一次:

element.attr({ 
    width: '100', 
    height: '100' 
}); 

element例如可以$('img')让所有<img>元素,或$('#imgId')以获得详细说明c <img id="imgId">元素。请参阅jQuery Selectors部分以了解有关选择元素的更多信息。

编辑:为您编辑的响应,毕竟你并不需要在widthheight属性“PX”后缀,他们已经隐含像素。当您想更改关联的CSS属性(如element.css('width', '100px');)时,只需要'px'。我相应地更新了我的答案。

+0

谢谢你,我在顶部更新了我的帖子,你认为它可以是什么? – sarmenhb 2009-11-25 02:16:46

0

jQuery对DOM中的元素进行操作,而不是元素的属性。

您需要一个选择器来选择您的img元素,然后编辑您的属性。

$("img").attr('width', '35px') 
$("img").attr('height', '35px') 

虽然你可能需要一个比“img”更具体的选择器。你的图片是否有班级或身份证?

+0

谢谢我更新了我的帖子,你认为它可以是什么? – sarmenhb 2009-11-25 02:17:18

1

您是否尝试过使用attr(key, value)

你可以这样做: $('img').attr('height', '50px'); $('img').attr('width', '50px');

+0

我试过了。出于某种原因,代码中的值是正确的,但是当在Firebug中检查该元素时,它将保留原始值。所以,实际上,没有任何改变。我有一个名为#right的ID。我想将它的宽度从68%改为97%,就像这个$(“#right”)。attr(“width”,“97%”);.代码说97%,Firebug 68%。我不明白。 – 2012-07-11 20:17:33

0

也许问题是与选择。尝试

$('td.productPhotoThumbnailSection').children().children('img').attr({ width: '100', height: '100' }) 

我试过了,那工作!

0

这样做:

$(function() { 
    $("td.productPhotoThumbnailSection img").attr({ 
    width: 64, 
    height: 64 
    }); 
}); 

注意,这是一个简单的数字( “64”),没有测量的单元( “64PX”)。后者是一个有效的CSS值,但不是有效的HTML值(对于该属性)。在这种情况下,唯一有效的计量单位是一个百分比。

参见IMG element from the HTML specification其中高度和宽度是类型%长度和%Length is defined为:

ン像素或NN%为百分比 长度

即 “64PX” 是无效的。