我刚刚浏览 Jbox 插件代码,特别是添加音频的部分,我遇到了以下代码:
jBox.prototype.audio = function(options) {
options || (options = {});
jBox._audio || (jBox._audio = {});
// URL required, no IE8 support
if (!options.url || this.IE8) return this;
// Create audio if it doesn't exist
if (!jBox._audio[options.url]) {
var audio = jQuery('<audio/>');
jQuery('<source/>', {src: options.url + '.mp3'}).appendTo(audio);
jQuery('<source/>', {src: options.url + '.ogg'}).appendTo(audio);
jBox._audio[options.url] = audio[0];
}
// Set volume and play audio
jBox._audio[options.url].volume = Math.min((options.volume != undefined ? options.volume :
(this.options.volume != undefined ? this.options.volume : 100) / 100), 1);
jBox._audio[options.url].pause();
try { jBox._audio[options.url].currentTime = 0; } catch (e) {}
jBox._audio[options.url].play();
return this;
};
我遇到困难的代码行如下:
try { jBox._audio[options.url].currentTime = 0; } catch (e) {}
这里为什么使用try catch?我理解 try catch 的用法,但在这段代码的上下文中我无法理解其用法。谁能解释一下吗?
我所说的这行代码可以找到 HERE 。
最佳答案
来自 HTML5 规范(强调我的):
On setting, if the media element has a current media controller, then the user agent must throw an InvalidStateError exception; otherwise, if the media element's readyState is HAVE_NOTHING, then it must set the media element's default playback start position to the new value; otherwise, it must set the official playback position to the new value and then seek to the new value.
它是为了处理浏览器尚不知道如何更新播放时间的情况。
关于javascript - 为什么在创建音频元素时要 try catch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31776576/