根据样式宽度+高度更改图像src
我有一个asp.net mvc项目和一个基于url参数流出图像的函数。例如:/ Image/40/100/50使用ImageID 40,100px宽和50px高的图像流传输图像。根据样式宽度+高度更改图像src
那么,有没有办法改变:
<img class="image" src="/Content/View?fileID=31" style="width: 500px; height: 100px; " />
要:
<img class="image" src="/Image/31/500/100" style="width: 500px; height: 100px; " />
在一些奇特的方式? /拉塞
我不知道我理解为什么你要做到这一点,但沿东西线以下应该做的伎俩:
$("img[src^='/Content/View?fileID=']").each(function() {
var img = $(this);
var id = img.attr("src").substring(21);
img.attr("src", "/Image/" + id + "/" + img.width().toString() + "/" + img.height().toString());
});
链接例如:http://jsfiddle.net/Cfdfp/2/
另外,如果你只应用image
类的img需要这种转变的元素,可以简化上述的选择:
$(".image").each(function() {
var img = $(this);
var id = img.attr("src").substring(21);
img.attr("src", "/Image/" + id + "/" + img.width().toString() + "/" + img.height().toString());
});
如何:
$('img').each(function() {
var $this = $(this),
id = $this.attr('src').substr($this.attr('src').indexOf('=')+1),
wid = $this.width(),
hgt = $this.height();
$this.attr('src','/Image/'+id+'/'+wid+'/'+hgt);
});
为什么使用'$ this.attr('width')'而不是'$ this.width()'?他希望尊重CSS宽度值,而不是属性_width_。 – Armin 2011-12-29 15:12:30
好点;固定。 – Blazemonger 2011-12-29 15:52:50
可以肯定的是,浏览器会在任何情况下加载原始图像!所以如果你想缩放图像以节省带宽,这是不正确的。 – Armin 2011-12-29 15:11:20