jQuery 从javascript加载图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19396390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:52:02  来源:igfitidea点击:

Load Image from javascript

javascriptjquery

提问by Deepak Malhotra

On my album slide show page, i have code like

在我的专辑幻灯片页面上,我有类似的代码

<span style="display:none;">
   <img id="id1" src="~$imageUrl`" onload="javascript:showImage();">
</span>

<span>
    // show loader.
</span>

in showImage(), i am sure the image is loaded, so i show the image and hide the loader.

在 中showImage(),我确定图像已加载,因此我显示图像并隐藏加载器。

Now when user clicks on next, i need to change the src of the image. Now i need don't know how to set src only when image is loaded.

现在,当用户单击下一步时,我需要更改图像的 src。现在我不需要知道如何仅在加载图像时设置 src。

回答by Adassko

you can just append another hidden imgelement and swap them in onloadevent.

您可以附加另一个隐藏img元素并在onload事件中交换它们。

Or use single image element and use javascript like:

或者使用单个图像元素并使用 javascript,如:

var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
    _img.src = this.src;
}
newImg.src = 'http://whatever';

this code should preload the image and show it when it's ready

此代码应预加载图像并在准备好时显示

回答by Jason Sebring

Sorry guys.

对不起大家。

You can't rely on the image load event to fire but you can kind of rely on it in some situations and fallback to a maximum load time allowed. In this case, 10 seconds. I wrote this and it lives on production code for when people want to link images on a form post.

您不能依赖图像加载事件来触发,但您可以在某些情况下依赖它并回退到允许的最大加载时间。在这种情况下,10 秒。我写了这个,它存在于生产代码中,当人们想要链接表单帖子上的图像时。

function loadImg(options, callback) {
  var seconds = 0,
  maxSeconds = 10,
  complete = false,
  done = false;

  if (options.maxSeconds) {
    maxSeconds = options.maxSeconds;
  }

  function tryImage() {
    if (done) { return; }
    if (seconds >= maxSeconds) {
      callback({ err: 'timeout' });
      done = true;
      return;
    }
    if (complete && img.complete) {
      if (img.width && img.height) {
        callback({ img: img });
        done = true;
        return;
      }
      callback({ err: '404' });
      done = true;
      return;
    } else if (img.complete) {
      complete = true;
    }
    seconds++;
    callback.tryImage = setTimeout(tryImage, 1000);
  }
  var img = new Image();
  img.onload = tryImage();
  img.src = options.src;
  tryImage();
}

use like so:

像这样使用:

loadImage({ src : 'http://somewebsite.com/image.png', maxSeconds : 10 }, function(status) {
  if(status.err) {
    // handle error
    return;
  }
  // you got the img within status.img
}); 

Try it on JSFiddle.net

在 JSFiddle.net 上试试

http://jsfiddle.net/2Cgyg/6/

http://jsfiddle.net/2Cgyg/6/

回答by Nikin Jasani

<span>
    <img id="my_image" src="#" />
</span>

<span class="spanloader">

    <span>set Loading Image Image</span>


</span>

<input type="button" id="btnnext" value="Next" />


<script type="text/javascript">

    $('#btnnext').click(function () {
        $(".spanloader").hide();
        $("#my_image").attr("src", "1.jpg");
    });

</script>

回答by leaf

Use a new image object each time you want to load a picture :

每次要加载图片时使用新的图像对象:

var image = new Image();
image.onload = function () {
    document.getElementById('id1').setAttribute('src', this.src);
};
image.src = 'http://path/to/image';

回答by bruhbruh

If you are loading the image via AJAX you could use a callback to check if the image is loaded and do the hiding and src attribute assigning. Something like this:

如果您通过 AJAX 加载图像,您可以使用回调来检查图像是否已加载并进行隐藏和 src 属性分配。像这样的东西:

$.ajax({ 
  url: [image source],
  success: function() {
  // Do the hiding here and the attribute setting
  }
});

For more reading refer to this JQuery AJAX

有关更多阅读,请参阅此JQuery AJAX

回答by Afzaal Ahmad Zeeshan

You can try this:

你可以试试这个:

<img id="id1" src="url/to/file.png" onload="showImage()">

function showImage() {
 $('#id1').attr('src', 'new/file/link.png');
}

Also, try to remove the ~, that is just the operator, that is needed for Server-Side (for example ASP.NET) you don't need it in JS.

此外,尝试删除~,这只是操作符,服务器端(例如 ASP.NET)所需的 JS 中不需要它。

This way, you can change the attribute for the image.

这样,您可以更改图像的属性。

Here is the fiddle: http://jsfiddle.net/afzaal_ahmad_zeeshan/8H4MC/

这是小提琴:http: //jsfiddle.net/afzaal_ahmad_zeeshan/8H4MC/

回答by Deepu

Try this.You have some symbols in $imageUrl

试试这个。你有一些符号 $imageUrl

<img id="id1" src="$imageUrl" onload="javascript:showImage();">

回答by Nabi

See this tutorial: Loading images with native JavaScript and handling of events for showing loading spinners

请参阅本教程:使用本机 JavaScript 加载图像和处理用于显示加载微调器的事件

It tells you how to load images with native JavaScript and how to handle events for showing loading spinners. Basically, you create a new Image(); and handle the event correctly then. That should work in all browsers, even in IE7 (maybe even below IE7, but I did not test that...)

它告诉您如何使用本机 JavaScript 加载图像以及如何处理用于显示加载微调器的事件。基本上,您创建一个新的 Image(); 然后正确处理事件。这应该适用于所有浏览器,甚至在 IE7 中(甚至可能低于 IE7,但我没有测试......)

回答by Ande Caleb

this worked for me though... i wanted to display the image after the pencil icon is being clicked... and i wanted it seamless.. and this was my approach..

虽然这对我有用......我想在点击铅笔图标后显示图像......我想要它无缝......这是我的方法......

pencil button to display image

显示图像的铅笔按钮

i created an input[file] element and made it hidden,

我创建了一个 input[file] 元素并将其隐藏,

<input type="file" id="upl" style="display:none"/>

this input-file's click event will be trigged by the getImage function.

这个输入文件的点击事件将由 getImage 函数触发。

<a href="javascript:;" onclick="getImage()"/>
    <img src="/assets/pen.png"/>
</a>

<script>
     function getImage(){
       $('#upl').click();
     }
</script>

this is done while listening to the change event of the input-file element with ID of #upl.

这是在侦听 ID 为 #upl 的输入文件元素的更改事件时完成的。

   $(document).ready(function(){
     
       $('#upl').bind('change', function(evt){
         
    var preview = $('#logodiv').find('img');
    var file    = evt.target.files[0];
    var reader  = new FileReader();
  
    reader.onloadend = function () {
   $('#logodiv > img')
    .prop('src',reader.result)  //set the scr prop.
    .prop('width', 216);  //set the width of the image
    .prop('height',200);  //set the height of the image
    }
  
    if (file) {
   reader.readAsDataURL(file);
    } else {
   preview.src = "";
    }
  
    });

   })

and BOOM!!! - it WORKS....

和繁荣!!!- 有用....

回答by Дмитрий Паймуллин

Simplest load image from JS to DOM-element:

最简单的从 JS 加载图像到 DOM 元素:

element.innerHTML += "<img src='image.jpg'></img>";

With onload event:

使用 onload 事件:

element.innerHTML += "<img src='image.jpg' onload='javascript:showImage();'></img>";