每次图像加载完成时运行一个函数

发布于 2024-12-09 00:48:30 字数 623 浏览 0 评论 0原文

我想知道如何使用 JQuery 创建一个函数,该函数将在每次图像加载完成时运行。我希望该函数每次都被调用,而不仅仅是一次。因此,例如,如果我有“image1.jpg”并且它是在页面开始时加载的,则将调用该函数。然后,如果我更改图像并且在使用 Javascript 更改图像后再次加载它,我希望再次触发“已加载”函数。我尝试了 Jquery Load() 函数,但它只运行一次,而不是在图像被替换为另一个图像后运行第二次。

我还希望即使图像也被缓存,事件也会发生。这意味着每次我更改图像的“src”属性时,我都希望再次启动特定的函数,即使图像已经被缓存。

示例:

$("#myimageselector").attr("src", "http://domain.com/the_new_image.jpg");

我希望当发生这种情况时,即使图像已经缓存,该函数也会触发。我认为有可能知道图像是否已被缓存。我只需要一个 .load() 函数,它会运行一次(当然),如果它没有被执行,则意味着图像已被缓存。至少对于我的具体用途来说。

想法:也许我们应该绑定一个事件来检查 DOM 中特定元素更改的变化。因此,如果图像已完成加载,则特定的 DOM 元素可能会发生更改,因此我们可以检查之前和之后的值。

谢谢。

I wanted to know how to use JQuery to create a function that will run on each time an image has been finished loading. I want that function to be called EACH TIME, not only once. So if, for example, I have "image1.jpg" and it was loaded on page start, the function will be called. Then, if I change the image and it was loaded again after I changed it using Javascript, I want that 'loaded' function to fire again. I tried Jquery Load() function, but it only run once, not the second time after the image has been replaced with another one.

I want also that the even will happen even if the image has been cached too. That means that every time I change thew 'src' attribute of the image, I want that a specific function to fire up - again, even if the image is already been cached.

Example:

$("#myimageselector").attr("src", "http://domain.com/the_new_image.jpg");

I want that when this happens, even if the image is already cached the function will fire. I think that it's possible to know if the images has been cached, kind of. I just need to have an .load() function that will run once (of course), and if it hasn't been executed, it means that the image has been cached. At least for my specific usage.

Thought: maybe we should bind an event that checked a change in the DOM for a specific element change. So maybe if the image has been finished loading, a specific DOM element is changed, so we can check the before and after values.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

岁月无声 2024-12-16 00:48:30

我最接近您想要的解决方案,还可以处理缓存的图像。
我创建了一个 jQuery 插件:

(function($){
    var dummy_img = "dummy1x1.png",
        dummy_width = 1,
        dummy_height = 1;

    $("<img>").attr("src", dummy_img); //Preload image

    $.fn.setSrc = function(src, func, args){
        var $img = this;
        if(/img/i.test(this.get(0).tagName)) return; //Cancel at non-IMG elements
        if(!(args instanceof Array)) args = [];
        var poller = window.setInterval(function(){
            if($img.height() != dummy_height || $img.width() != dummy_width){
                loaded();
            }
        }, 200);
        $img.attr("src", dummy_img);
        $img.bind("load", loaded);
        $img.bind("error", clearPoller);
        function loaded(){
            clearPoller();
            //If a callback function exists, execute it
            if(typeof func == "function") func.apply($img,args);

            func = null;//Prevent unwanted executions
        }
        function clearPoller(){
            window.clearInterval(poller);
        }
    }
})(jQuery);

用法:

$("#myImg").setSrc("image.png", function(){
    alert(this.attr("src") + " has loaded!");
});

背后的概念:

  1. 将宽度和高度更改为 1(使用预加载的虚拟图像)
  2. 绑定 loaderror 事件处理程序
  3. 运行轮询器检查图像的宽度和高度。
  4. 当图像加载完成/失败时,将触发 loaderror 事件。触发后,轮询器被清除,并执行传递的函数。
  5. 当这些事件都没有被触发时,轮询器仍然能够检测到图像大小的变化。当加载缓存的图像时,元素的宽度/高度会更新,这是由轮询器检测到的。在这种情况下,轮询器清除间隔,并执行传递的函数。

The closest I get to your desired solution, to also deal with cached images.
I've created a jQuery plugin:

(function($){
    var dummy_img = "dummy1x1.png",
        dummy_width = 1,
        dummy_height = 1;

    $("<img>").attr("src", dummy_img); //Preload image

    $.fn.setSrc = function(src, func, args){
        var $img = this;
        if(/img/i.test(this.get(0).tagName)) return; //Cancel at non-IMG elements
        if(!(args instanceof Array)) args = [];
        var poller = window.setInterval(function(){
            if($img.height() != dummy_height || $img.width() != dummy_width){
                loaded();
            }
        }, 200);
        $img.attr("src", dummy_img);
        $img.bind("load", loaded);
        $img.bind("error", clearPoller);
        function loaded(){
            clearPoller();
            //If a callback function exists, execute it
            if(typeof func == "function") func.apply($img,args);

            func = null;//Prevent unwanted executions
        }
        function clearPoller(){
            window.clearInterval(poller);
        }
    }
})(jQuery);

Usage:

$("#myImg").setSrc("image.png", function(){
    alert(this.attr("src") + " has loaded!");
});

The concept behind this:

  1. Change width and height to 1 (using the preloaded dummy image)
  2. Bind load and error event handlers
  3. Run a poller which checks for the width and height of the image.
  4. When the image has finished/failed loading, the load or error event will be triggered. Upon triggering, the poller is cleared, and the passed function is executed.
  5. When none of these events are fired, the poller is still able to detect a change in image size. When the cached image is loaded, the width/height of the element updates, which is detected by the poller. In this case, the poller clears the interval, and executes the passed function.
吖咩 2024-12-16 00:48:30

您可以对 Img 标签使用 onLoad 函数

$(".img").load(function (){
    // do something
});

you can use the onLoad function for the Img tag

$(".img").load(function (){
    // do something
});
半城柳色半声笛 2024-12-16 00:48:30
$('img').live('load', function ()
{
    alert("image loaded: "+this.src);
});

使用 jquery live 方法来跟踪负载。

$('img').live('load', function ()
{
    alert("image loaded: "+this.src);
});

Use jquery live method to track load.

指尖微凉心微凉 2024-12-16 00:48:30

无论图像是否被缓存,这都会运行:

$(document).ready(function() {
    var imgLoadFunc = function() {
        //code to run
    };

    $("img").each( function() {
        if(this.complete) {
            imgLoadFunc.call(this);
        } else {
            $(this).load( function() {
                imgLoadFunc.call(this);
            });
        }
    });
});

严格来说,您不需要使用 call(),但这将允许您以更 jquery 的方式使用有问题的图像元素。 imgLoadFunc 内部:

var img = $(this);

This will run whether image is cached or not:

$(document).ready(function() {
    var imgLoadFunc = function() {
        //code to run
    };

    $("img").each( function() {
        if(this.complete) {
            imgLoadFunc.call(this);
        } else {
            $(this).load( function() {
                imgLoadFunc.call(this);
            });
        }
    });
});

Strictly speaking, you don't need to use call(), but this will allow you to use the image element in question in a more jquery-ish way. Inside imgLoadFunc:

var img = $(this);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文