【问题标题】:How to get the original size of an image -Jquery如何获取图像的原始大小-Jquery
【发布时间】:2012-08-28 14:21:19
【问题描述】:

已解决:语法错误

以下代码有效:

var image = {width:0,height:0};
var imageObject = new Image();
function getImageSize(id) {
    imageObject.src = id.attr("src");
    image.width = imageObject.width;
    image.height = imageObject.height;
}

原始问题

我想获取图像的原始宽度和高度,并尝试了不同的代码来实现它。我的函数在点击事件时触发,所有图像都调整为 400x300。

我尝试使用 auto 将图像调整为原始大小:

var image = {width:0,heigth:0};
function getImageSize(id) {
    id.css({
        'width': 'auto',
        'heigth': 'auto'
    });
    image.width = id.attr('width');
    image.heigth = id.attr('heigth');
}

附加auto 并没有改变图像的大小。

alert(id.attr('width')); 总是返回“未定义”。所以它不起作用

var image = {width:0,heigth:0};
var imageObject = new Image();
function getImageSize(id) {
    imageObject.src = id.attr("src");
    image.width = imageObject.width;
    image.heigth = imageObject.heigth;
}

alert(image.width); 完美运行。

alert(image.heigth); 返回未定义。

使用imageObject.naturalWidth 与上面的一样 - 正确给出了宽度,但未定义高度。

我读到您必须附加新的图像对象,但是当我使用 imageObject.appendTo('body'); 时,我什至无法单击图像。

感谢您的任何建议。

【问题讨论】:

  • 一旦你改变了图像大小,自动不会再把它带回来。至于获取图片的大小,必须先加载。
  • image.heigth 语法错误:“高度”
  • 哦,我写错了很多次,改变语法解决了它

标签: jquery height width


【解决方案1】:

这是一个简单的包含示例,将图像替换为更改后具有其原始大小的图像。

<img src="http://www.finesttreeserviceaz.com/wp-content/uploads/2012/02/tree2.gif" id="bar" />
<script type="text/javascript">
    var myImg = document.getElementById("bar");
    myImg.setAttribute("style", "width:400px;height:300px;");
    function resetBar() {
        var newImg = new Image();
        var oldImage = document.getElementById("bar");
        newImg.src = oldImage.src;
        oldImage.parentNode.replaceChild(newImg, oldImage);
    }
    setTimeout("resetBar();", 2000);
</script>

另一种方法是删除应用的样式:

myImg.removeAttribute("style");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-11
    • 2012-01-24
    • 2015-11-15
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    相关资源
    最近更新 更多