加载图像后启动转换事件

时间:2016-04-05 14:29:21

标签: javascript css

我在进行转换时遇到问题,包含图像的div应该来自“right:200px;”到“400px”进行2s的转换,转换应该在文档中加载图像时开始,这里是css代码:

    div.contenedor {
        width: 300px;
        height: 257px;
        position: fixed;
        right: 200px;
        bottom: 0px;
        z-index: 100;
        -webkit-transition: right 2s;
        -moz-transition: right 2s;
        transition: right 2s;
    }

这里是js代码:

        function transi() {
            var id = "L" + Math.floor(Math.random() * 10000);
            function open() {
                var eOpen = document.getElementById(id + "_container");
                    eOpen.style.right = "400px";
            };

            var dContenedor = document.createElement("div");
            dContenedor.id = id + "_container";
            dContenedor.className = "contenedor";

            var ima = document.createElement("img");
            ima.src = "XXXX.jpg";
            ima.width = "300";
            ima.height = "250";

            dContenedor.appendChild(ima);

            document.onreadystatechange = function(){
                var rsw = this.readyState;
                console.log(rsw);
                if (rsw) if (rsw != 'complete') if (rsw != 'loaded') {return;}
                document.body.appendChild(dContenedor);
                console.log(ima.complete);
                if (ima.complete) {
                    open();
                };
            }
        };
        transi();

出于某种原因,没有进行过渡,并且div将直接转到“400px”,如果有人有一些想法我会贬低它,谢谢你的支持

1 个答案:

答案 0 :(得分:2)

也许在load图像事件上调用函数?

<强> UPD 添加了工作示例

function transi() {
  var id = "L" + Math.floor(Math.random() * 10000);
  var dContenedor = document.createElement("div");
  dContenedor.id = id + "_container";
  dContenedor.className = "contenedor";

  function open() {
    // we already have ref to needed element
    dContenedor.style.right = "400px";
  };

  var ima = document.createElement("img");
  ima.width = "300";
  ima.height = "250";

  dContenedor.appendChild(ima);
  document.body.appendChild(dContenedor);
  // when image is loaded fire event
  ima.onload = function() {
    open();
  }
  ima.src = "https://v1.std3.ru/32/9b/1455811008-329b55c554efcec3988dc8ab44eb972f.jpeg";
};
transi();
   div.contenedor {
     width: 300px;
     height: 257px;
     position: fixed;
     right: 200px;
     bottom: 0px;
     z-index: 100;
     -webkit-transition: right 2s;
     -moz-transition: right 2s;
     transition: right 2s;
     background: #333;
   }