【问题标题】:Javascript loading an imageJavascript加载图像
【发布时间】:2014-11-15 11:53:26
【问题描述】:

我有一个字段和一个图像容器。

在这个容器中有一个默认图像。

我希望用户放置图片的链接然后提交,然后将图片添加到 默认图片的src属性。

我的问题,我应该如何加载图像,在此期间向用户显示一个进度条,加载完成后,隐藏 URL。我现在主要关心的是如何加载资源。

现在我已经编写了这个脚本:

jQuery("#logo-file-upload").on("click", function(){
// when user clicks the submit button

    $("#url-logo-progress").show(); // show the progress bar to it

    var logoUrl = $("#logo-url").val(); // pick up the inserted URL

    $("#image-width").attr("src", logoUrl); // and put the URL into the src attribute of the image

});

虽然我需要这样的东西:

$.imageLoad({ url : "url/to/image.jpg", 
    complete : function(){
    alert("upload finished!");
    });

我写回调和状态没有问题,但我不知道如何加载资源。

提前致谢

【问题讨论】:

标签: javascript jquery html image


【解决方案1】:

您只是错过了 onload 处理程序。当您在图像(DOM 图像元素)上设置 src 属性时,它开始加载资源。当资源加载完毕后,图片会触发onload事件。

所以,而不是

jQuery("#logo-file-upload").on("click", function(){
// when user clicks the submit button

    $("#url-logo-progress").show(); // show the progress bar to it

    var logoUrl = $("#logo-url").val(); // pick up the inserted URL

    $("#image-width").attr("src", logoUrl); // and put the URL into the src attribute of the image

});

jQuery("#logo-file-upload").on("click", function(){
// when user clicks the submit button

    $("#url-logo-progress").show(); // show the progress bar to it

    var logoUrl = $("#logo-url").val(); // pick up the inserted URL

    var image = $("#image-width")[0];

    image.onload = function(){alert("upload finished!");}

    image.src = logoUrl; // and put the URL into the src attribute of the image

});

这样您就可以直接处理对 Image DOM 元素的引用,而不是使用 jQuery 引用。当然,加载资源时,您将不得不隐藏进度条等...而不仅仅是提醒消息。

【讨论】:

    猜你喜欢
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 2012-07-04
    • 2021-09-20
    • 2011-02-22
    相关资源
    最近更新 更多