简体   繁体   English

Javascript。 为什么此代码不起作用?

[英]Javascript. Why does not work this code?

I can not call the property height: 我不能称该属性的高度:

When I call the height property, the message get 0. But it should give me 1152. 当我调用height属性时,消息得到0。但是它应该给我1152。

var fondoJuego=new FondoJuego();
fondoJuego.setFondoSrc("tituloNV.png");
alert("Altura "+fondoJuego.getFondo().height);

var FondoJuego=function(){
            this.fondo=new Image();
            this.getFondo=function(){
                return this.fondo;
            };
            this.getFondoSrc=function(){
                return this.fondo.src;
            };
            this.setFondo=function(fondoAux){
                this.fondo=fondoAux;
            };
            this.setFondoSrc=function(fondoSrcAux){
                this.fondo.src=fondoSrcAux;
            };
        };

Thanks 谢谢

This happens because of the image takes some time to load in a async fashion 发生这种情况是因为图片需要花费一些时间以async fashion加载

Let's take Google's Doodle as an example: 让我们以Google的Doodle为例:

var imageAsync = new Image();
imageAsync.src = "https://www.google.com.br/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png?t=" + (+new Date);
console.log(imageAsync.height);

var imageSync = new Image();
imageSync.src = "https://www.google.com.br/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png?t=" + (+new Date);
imageSync.onload = function () {
  console.log(this.height);
}

Returns 0 and 92. 返回0和92。

You will need to listen to the load event. 您将需要监听load事件。

This should work: 这应该工作:

function getHeight() {
    alert("Altura " + fondoJuego.fondo.height );
    return true;
}

var FondoJuego = function() {

    this.fondo = new Image();

    this.fondo.addEventListener("load", function(){
        getHeight();
    });

    this.getFondo=function(){
        return this.fondo;
    };

    this.getFondoSrc=function(){
        return this.fondo.src;
    };

    this.setFondo=function(fondoAux){
        this.fondo=fondoAux;
    };

    this.setFondoSrc=function(fondoSrcAux){
        this.fondo.src=fondoSrcAux;
    };
};

var fondoJuego = new FondoJuego();

fondoJuego.setFondoSrc("tituloNV.jpg");

check this jsfiddle: https://jsfiddle.net/dm7dqajf/ 检查此jsfiddle: https ://jsfiddle.net/dm7dqajf/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM