【发布时间】:2014-11-03 10:54:53
【问题描述】:
假设我有一个实际宽度为1000px 的图像,但它在CSS 中的宽度设置为100%,并且包含在500px 宽div 中。
有没有办法让jQuery知道图像实际上是1000px宽,即使它在页面上的宽度只有500px?
【问题讨论】:
假设我有一个实际宽度为1000px 的图像,但它在CSS 中的宽度设置为100%,并且包含在500px 宽div 中。
有没有办法让jQuery知道图像实际上是1000px宽,即使它在页面上的宽度只有500px?
【问题讨论】:
是的,使用naturalWidth:
var realWidth = imgElement.naturalWidth;
【讨论】:
naturalWidth。)
您可以做的是使用相同的src 离页创建一个新图像,并对其进行测量。
例如,如果您现有的 img 元素具有 id "foo",那么:
$("<img>")
.css({
position: "absolute",
left: -10000,
top: 0
})
.on("load", function() {
var realWidth = this.width;
var realHeight = this.height;
$(this).remove();
// Use `realWidth` and `realHeight` here
})
.appendTo(document.body)
.attr("src", $("#foo").attr("src"));
【讨论】:
img { width: 100%; } 破坏吗?
img 元素的宽度,它可能会受到影响,是的。 (不过,我认为您的具体示例不会影响上述内容。)