单击链接时在新选项卡上运行音频 - HTML



我知道通过下面的代码音频会播放....

<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

我希望如果我单击一个链接,然后打开一个新窗口并开始播放音频......知道怎么做吗?

附言这是一种方法。但我不想制作任何额外的 HTML 页面。

你可以使用javascript来实现这一点。

例如,使用 JQuery,您可以创建 2 个函数,如下所示:

function newTabFunction() {
    var w = window.open();
    var html = $("#newTab").html();
    $(w.document.body).html(html);
}
$(function() {
    $("a#link").click(newTabFunction);
});

第二个函数将在用户单击此链接时执行:

<a href="javascript:;" id="link">Open music</a>

newTabdiv 包含音乐播放器:

<div id="newTab">
    <p>The music is playing in a new tab</p>
    <audio controls autoplay>
        <source src="horse.ogg" type="audio/ogg">
        <source src="horse.mp3" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>
</div>

最后,这里有一个JS小提琴来向您展示结果是什么。

最新更新