简体   繁体   English

图像加载后如何使Alert运行?

[英]How to make Alert to run after the image is loaded?

I have this code and I want that the alert will pop up only after the backgroundImage is loaded. 我有此代码,我希望仅在加载backgroundImage之后才会弹出警报。

$('#element').click(function(){
    $('#element').css({
        backgroundImage: "url('http://www.button.jpg')",
        backgroundRepeat: 'no-repeat',
        backgroundPosition: '7px 5px'});;

alert ("button is loaded");

The button.jpg is a small size: 3 KB. button.jpg很小:3 KB。
But when I click on the button element, first the ALERT pop up, and 2 seconds after the image is complete loding. 但是,当我单击按钮元素时,首先弹出ALERT,然后在图像完全放置2秒后弹出。

I read about callBack 我了解了有关回拨的信息
Also about Delay() 也关于Delay()
Also about timeout 关于超时

But I am new in coding, and didn't understand what and how should I do here. 但是我是编码方面的新手,不了解在这里应该怎样做。

You would set up a load event on the image first. 您将首先在图像上设置load事件。

var imgSrc = 'http://www.button.jpg';

$('#element').click(function() {

    var img = new Image,
        element = $(this);

    img.onload = function() {

        element.css({
            backgroundImage: "url('" + imgSrc + "')",
            backgroundRepeat: 'no-repeat',
            backgroundPosition: '7px 5px'
        });

        alert("button is loaded");

    }

    img.src = imgSrc;

});

jsFiddle . jsFiddle

Then, when the image has been loaded, the load callback will be called and the background will be updated. 然后,在加载图像后,将调用加载回调并更新背景。

If you need to support IE6 and are finding it won't cooperate by downloading the image again you may need to look into a workaround . 如果您需要支持IE6并且发现无法通过重新下载映像进行合作,您可能需要研究解决方法

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

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