jquery - 为什么此图像/图像元素大小为 0px?

标签 jquery css

我有这个图像标签:

<img id="sidebar" src="images/homepageSidebar.jpeg" style="max-height:800px; float:left; padding-left:10px;"/>

我正在尝试获取图像宽度,以便可以在其旁边放置文本。当我执行以下函数时,我得到的 sidebarWidth 为 0px:

$(document).ready(function (){
    var sidebarWidth = $('#sidebar').width(),
        introPosition = sidebarWidth + 10;

    $('#intro').css({ left:introPosition });

    console.log(sidebarWidth);
    console.log(introPosition);

});

有人看出我的错误是什么吗?谢谢。

最佳答案

$(document).ready 在构建 DOM 时但在加载所有资源(如图像)之前触发。您必须使用 window.load 事件。

$(window).on('load', function (){
    var sidebarWidth = $('#sidebar').width(),
        introPosition = sidebarWidth + 10;

  $('#intro').css({ left:introPosition });

  console.log(sidebarWidth);
  console.log(introPosition);

});

关于jquery - 为什么此图像/图像元素大小为 0px?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17514182/

相关文章:

javascript - 观察div中的属性变化

javascript - 选项标签 : how to show multiple classes

jquery - HighCharts 设置滚动条位置

jquery - 如何在设置高度后获取图像的宽度

jquery - CSS3 动画和更新 DOM

jquery - 自定义从 map 制作者嵌入的谷歌地图

html - 2个并排的div,每个50%,高度相同

javascript - 使用 JavaScript 从 XML 节点检索内部文本时遇到问题

html - 如何将容器的原点更改为其内部元素

html - 是否可以只扩展响应图像的宽度?