如何在IE中更改src后获得新的图像大小
How to get new image size after changing src in IE
我有一个带有旋转控件gif的图像元素。后来我用jQuery动态地更改了图像的src,我想获得新图像的实际宽度和高度。下面是我的代码:
function loadImage() {
$('#uploaded-image').load(function() {
var img = document.getElementById('uploaded-image');
// These statements return the correct values in FF and Chrome but not IE
imgWidth = img.clientWidth;
imgHeight = img.clientHeight;
});
$('#uploaded-image').removeAttr('width').removeAttr('height').attr('src', imgUrl);
}
这在Chrome和Firefox中工作得很好,但IE总是返回原始旋转器gif的大小,而不是新图像。
如何在IE中获得新图像的宽度和高度?
指出:
除了纯Javascript方法外,我还尝试了jQuery .width()和.height()方法,结果相同。
.load事件在所有浏览器中按预期触发
在IE中使用offsetHeight
和offsetWidth
在IE中查看:http://jsbin.com/abopih/5
var imgUrl = "http://www.google.com/intl/en_com/images/srpr/logo3w.png";
var img = document.getElementById('uploaded-image');
$('#uploaded-image').click(function() {
imgWidth = img.clientWidth;
imgHeight = img.clientHeight;
$('#uploaded-image').removeAttr('width').removeAttr('height').attr('src', imgUrl);
console.info('clientWidth: ', img.clientWidth);
console.info('clientHeight: ', img.clientHeight);
console.info('offsetWidth: ', img.offsetWidth);
console.info('offsetWidth: ', img.offsetWidth);
});
您可以创建一个隐藏的div并将图像放置在其中以获得大小。只要确保隐藏的div没有完成display:none
,因为它将没有尺寸。使用visibility:hidden
,抓取尺寸,然后删除它
确保你也删除了css的height和width:
$('#uploaded-image').css({ height: "auto", width: "auto" });
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file" id="file" />
<script type="text/javascript" charset="utf-8">
$("#file").change(function(e) {
var file, img;
file = document.getElementById("file");
if (file!=null) {
img = new Image();
img.src = file.value;
img.onload = function() {
alert(img.width + " " + img.height);
};
img.onerror = function() {
alert( "not a valid file: " + file.type);
};
}
});
</script>
似乎是缓存问题。
添加到你的图片源url:
imgUrl += new Date().getTime();
相关文章:
- Javascript将图像src更改为淡入淡出
- 在字符串中查找所有图像 src URL 并存储在数组中
- 如何使用javascript和xpath获取图像src
- 使用带有变量的javascript更改图像src
- 用jquery抓取图像SRC-attr
- MVC5更改jquery脚本中的图像src
- 隐藏或删除图像 src=未定义
- JavaScript 动态更改图像 src 的位置 - NO JQuery
- 如何使用 jquery、声音/静音按钮更改图像 SRC onclick
- 有没有一种方法可以判断图像src是否在javascript内部返回null
- 更改图像src-dons't工作jquery/js
- 将图像加载到localStorage,并将图像src设置到该位置
- 需要多次使用getElementById来更改图像src
- 如何更改多个图像的图像src
- 加载后修改页面上所有没有id的图像(src)
- 带有图像 src 的 JavaScript 点击事件
- 如果屏幕宽度 <= 699,则交换图像 src
- 更换部分图像 src
- 从没有jQuery的字符串中获取图像src
- 保存图像 src 的功能不起作用