Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 为什么可以';我不能得到图像的自然宽度吗?_Jquery - Fatal编程技术网

Jquery 为什么可以';我不能得到图像的自然宽度吗?

Jquery 为什么可以';我不能得到图像的自然宽度吗?,jquery,Jquery,我想要获取其自然大小的图像的URL存储为数据标记,如下所示: <div class="background_one" data-image="//localhost:3000/my_project/wp-content/uploads/2017/03/case_2_desk-1.jpg"></div> 它应该能工作,但不能。alert()显示“宽度:0和高度:0”。为什么?您是否尝试过: image.onload = function() { console.log(t

我想要获取其自然大小的图像的URL存储为数据标记,如下所示:

<div class="background_one" data-image="//localhost:3000/my_project/wp-content/uploads/2017/03/case_2_desk-1.jpg"></div>
它应该能工作,但不能。
alert()
显示“宽度:0和高度:0”。为什么?

您是否尝试过:

image.onload = function() { console.log(this.height); };
是否已将代码添加到document.ready函数中,如下所示:

$(document.ready(function(){ // your code });

因为它还没有加载

您需要等待
load
事件,然后才能访问图像尺寸

$('.background_one').each(function(){
    var image = new Image();
    image.onload = function(){
       alert('width: ' + image.naturalWidth + ' and height: ' + image.naturalHeight);
    };
    image.src = $(this).data('image');
});

image.onload(function({});似乎永远不会触发。@drake035是的,你是对的。我用jquery语法思考。更正了。这是正确的答案,非常感谢!但我意识到@Kaloyan在你之前1分钟已经有了正确的答案,所以为了公平起见,我验证了他的答案。@drake035不是问题。
$('.background_one').each(function(){
    var image = new Image();
    image.onload = function(){
       alert('width: ' + image.naturalWidth + ' and height: ' + image.naturalHeight);
    };
    image.src = $(this).data('image');
});