gpt4 book ai didi

jquery - 在 jQuery 中获取图像的原始宽度和高度

转载 作者:行者123 更新时间:2023-12-03 22:23:51 25 4
gpt4 key购买 nike

我需要获取给定特定来源的图像的原始宽度和高度。我目前的方法是:

img.tag = "<img style='display:none;' src='" + img.src + "' />";
img.Owidth = 0;
img.Oheight = 0;

$(img.tag).load(function() {
img.Owidth = $(this).width();
img.Oheight = $(this).height();
}).appendTo(img.parent());

其中 OwidthOheight 是加载图像的原始尺寸。我想知道是否有更好的方法来做到这一点:

  • 图像可能已加载,但显示的尺寸与原始尺寸不同。
  • 图像尚未加载

最佳答案

跨浏览器:

jsFiddle demo

$("<img/>").load(function(){
var width = this.width,
height = this.height;
alert( 'W='+ width +' H='+ height);
}).attr("src", "image.jpg");
<小时/>

HTMLImageElement 属性/HTML5 兼容浏览器

如果您想调查所有 HTMLImageElement 属性:https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement
其中许多属性已在现代的兼容 HTML5 的浏览器中提供,并且可以使用 jQuery 的 .prop() metod 进行访问。

jsFiddle demo

var $img = $("#myImage");

console.log(
$img.prop("naturalWidth") +'\n'+ // Width (Natural)
$img.prop("naturalHeight") +'\n'+ // Height (Natural)
$img.prop("width") +'\n'+ // Width (Rendered)
$img.prop("height") +'\n'+ // Height (Rendered)
$img.prop("x") +'\n'+ // X offset
$img.prop("y") // Y offset ...
);

关于jquery - 在 jQuery 中获取图像的原始宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11513313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com