img onload事件

来源:互联网 发布:数据挖掘算法的作用 编辑:程序博客网 时间:2024/05/16 12:30

看了网上一些代码都不成功

下面特写一段代码

首先,整一个地方把src存起来

<input type="hidden" value="http://aa.com/a.jpg" id="hidheadimgsrc" />

再整一个图片对象,先写onload事件,再去赋src值。onload执行完后,再去赋值给img

var headimg = new Image();
headimg.onload=function(){
        var h = headimg.height;
        var w = headimg.width;
        $(".w1000-right .belonger-msg .rel img").css("margin-top", "-" + h / 2 + "px");
        $(".w1000-right .belonger-msg .rel img").css("margin-left", "-" + w / 2 + "px");
        if (w > 188) {
            $(".w1000-right .belonger-msg .rel img").width(188);
            $(".w1000-right .belonger-msg .rel img").height(252);
            $(".w1000-right .belonger-msg .rel img").css({ "margin-left": "-94px", "margin-top": "-126px" });

$(".w1000-right .belonger-msg .rel img")[0].setAttribute('src',headimg.src); 
        };
};
headimg.src = $("#hidheadimgsrc").val();

0 0
原创粉丝点击