【问题标题】:Calculate the width of an image in jQuery在jQuery中计算图像的宽度
【发布时间】:2013-08-03 14:35:48
【问题描述】:

我有一个image,即height 是浏览器的100%widthauto。因此,宽度可能会因图片和屏幕分辨率而异。

所以,我想计算浏览器中未被图像占用的宽度。

.main-image img {
    width:auto
}

var winheight = $(window).height();

$('.main-image img').css('height', winheight);

所以,我正在考虑做这样的事情,但它不会奏效。

   var findimage = $('.main-image img');
   var imagewidth = findimage.clientHeight;
   console.log("image width is " + imagewidth);

但是,这个returnsimage width is undefined”。我该怎么办?

【问题讨论】:

标签: jquery css


【解决方案1】:

请记住,图像不是标记的一部分,因此必须先加载它,然后才能检索它的宽度。

$('.main-image img').onload(function () {
    console.log("image width is " + $(this).width());
});

【讨论】:

  • 我会说你可以只做this.width onload。除非您有其他用途,否则没有理由创建 jQuery 对象。但这绝对是正确的。
  • @kalley 你是对的,this.width 可以工作,而且效率更高,因为它不必由 jQuery 插件解释。
  • 未捕获类型错误:对象 [object Object] 没有方法 'onload'
【解决方案2】:

尝试使用

$('.main-image img').width()
$('.main-image img').height()

并使用Offset 定位左/上

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-26
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    相关资源
    最近更新 更多