文档就绪时元素宽度未定义
我试图在 之前使用以下代码获取元素宽度,
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var diff = $('div.canvas img.photo').get(1).width;
console.log(diff);
});
</script>
但它记录未定义。但是,如果我直接在 Chrome/Firebug 控制台中运行 $('div.canvas img.photo').get(1).width
,它会返回正确的宽度。该图像未使用 Javascript 加载,因此当文档准备就绪时应该已就位。我做错了什么?
I am trying to obtain an element width using the following code just before the </body>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var diff = $('div.canvas img.photo').get(1).width;
console.log(diff);
});
</script>
but it logs undefined. However, if I run $('div.canvas img.photo').get(1).width
directly in the Chrome/Firebug console, it returns the correct width. The image is not being loaded with Javascript, so should be in place when the document ready fires. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,不应该。 document.ready 在加载所有 HTML(但不包括图像)时触发。如果您想等到所有图像加载完毕,请使用 window.load。
示例:
此外,正如一些人指出的那样,您试图两次获取属性“.width”。
如果可能的话,在 CSS 中设置图像标签的宽度。这样,您就可以安全地在代码中使用 document.ready。使用 window.load 自然会延迟脚本的执行,可能是一秒,也可能是十秒,具体取决于客户端连接的速度以及页面上的内容量。如果您执行任何样式设置,这可能会导致不必要的跳跃和抖动。
No, it shouldn't. document.ready fires when all HTML has been loaded, but not the images. If you want to wait until all images are loaded, use window.load.
Example:
Also, as some people have pointed out, you were attempting to get the property ".width" twice.
If at all possible, set a width on the imagetags in CSS. That way, you can safely use document.ready for your code. Using window.load will naturally delay the execution of your script, could be a second, could be ten, depending on the speed of the clients connection, and the amount of content on your page. This could cause unwanted jumps and jitters if you're performing any styling.
img 尚未加载到 DOM 上。 文档:
改成这样:
img isn't being loaded on DOM ready. docs:
change to this:
图像的宽度仅在完全加载时才可用。
jQuery 也支持每个图像的 onload 事件。
你可以使用,
Image's width would only be available when its loaded completely.
jQuery supports onload event on every images too.
You can use,
问题是当您尝试获取其尺寸时,您的图像尚未加载。为了使其正常工作,请将您的代码包装到
$(window).load
中。或者另一种选择。如果您知道图像的大小,则可以提供width
和height
属性,那么即使在 DOMContentLoaded 中它也能工作。有时这是更好的选择,因为 onload 事件比“DOMContentLoaded”需要更长的时间来触发。否则,您需要使用
$(window).load
,请参阅@Andreas Carlbom 答案。The problem is that your image is not loaded yet when you try to get its dimentions. To make it work wrap your code into
$(window).load
. Or another option. If you know the sizes of the image you can providewidth
andheight
attributes, then it's going to work even inside DOMContentLoaded. Sometimes it's preferable because onload event takes longer to fire then 'DOMContentLoaded'.Otherwise you would need to use
$(window).load
, see @Andreas Carlbom answer.