仅在加载图像/声音时执行功能,Jquery

时间:2016-09-05 16:57:16

标签: javascript jquery image audio load

当窗口/文档已经加载时,我动态设置图像和音频源,例如我在用户对页面执行一些操作后设置它们:

// image and audio set
jQuery("#image").css('background-image', 'url(../content/icons/1/18.png)').css('backgroundPosition', '0 -40px');
var myAudio = new Audio('http://domain/content/audio/1/full-18.mp3');
myAudio.pause();

// i want this part of code be executed only when images and audio is fully loaded
myAudio.play();

解决方案编号1,无法正常工作

jQuery("#page").load(function() {});

解决方案编号2,无法正常工作

jQuery(window).load(function() {});

任何其他想法如何解决这个问题?提前谢谢

1 个答案:

答案 0 :(得分:0)

您需要专门定位图像元素以检查它是否已加载。

$('#image').load(function () {
    console.log('image loaded');
});

要检查音频元素是否已准备好播放,您需要使用onloadeddata

var myAudio = new Audio('http://www.mfiles.co.uk/mp3-downloads/edvard-grieg-peer-gynt1-morning-mood.mp3');
myAudio.onloadeddata = audioIsLoaded();

function audioIsLoaded() {
  console.log('audio is loaded');
}

运行以下代码段以查看此操作。



$('#image').load(function() {
  alert('image loaded');
});
var myAudio = new Audio('http://www.mfiles.co.uk/mp3-downloads/edvard-grieg-peer-gynt1-morning-mood.mp3');
myAudio.onloadeddata = audioReady();

function audioReady() {
  alert('audio ready');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="image" src="http://armpit-wrestling.com/wp-content/uploads/2016/06/bret-hart.jpg">
&#13;
&#13;
&#13;