javascript - 为什么在创建音频元素时要 try catch

标签 javascript jquery

我刚刚浏览 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/

相关文章:

javascript - jQuery 代码将所有内容隐藏在我的 div 中

javascript - 如何使用 jQuery 选择具有自定义类名的元素

jQuery 通过向上滑动/向下滑动替换淡入淡出效果

javascript - 动态加载 jQuery Mobile 导致 IE 最小化

javascript - 选择后更改选择选项显示的文本但在更改选择时返回

javascript - 如何确定事件是否从滚动条触发

javascript - 水平格式化 JavaScript 输出而不是垂直列表

javascript - 我可以创建一个不打开滚动条的元素吗?

javascript - CSS margin-top 和 top 没有绑定(bind)

javascript - Angular 4 上下文中的 "deep import"是什么?