两次单击不同网(文本和图像)并播放音频

时间:2017-02-01 07:16:19

标签: javascript html5-audio

我有一个文字和图片,我为每个onclick="playAudio()"添加了一个属性。

<h1 class="underline-on-hover" onclick="playAudio()" onmouseover="" cursor: pointer;">Test.</h1>
<img onclick="playAudio()" onmouseover="" style="cursor: pointer;" class="img-responsive" src="imagetest.png" alt="Image Test">

我想做以下事情。如果我单击文本播放音频,否则如果我单击图像停止播放文本音频和播放图像音频。 怎么做到?

HTML音频。

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

和JS。

var x = document.getElementById("myAudio");
function playAudio() {
    x.play();
}

3 个答案:

答案 0 :(得分:0)

请在下面的代码段this作为参数找到,这样我们就可以获得点击元素的tagName,而不是相应地设置条件。

&#13;
&#13;
var x = document.getElementById("myAudio");
function playAudio(e) {
  if(e.tagName == "IMG")
    {
     alert('Stop') ; 
    }
  if(e.tagName == "H1")
    {
     alert('Play') ;
    }
  
}
&#13;
<h1 class="underline-on-hover" onclick="playAudio(this)" onmouseover="" cursor: pointer;">Test.</h1>
<img onclick="playAudio(this)" onmouseover="" style="cursor: pointer;" class="img-responsive" src="imagetest.png" alt="Image Test" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

标记的多个音频源无法正常工作。

如果您只需要在文字点击后立即点击图片,那么这样的事情就可以了。

	var img = document.getElementById("img");
	function playAudio() {
		x = new Audio("sound.mp3");
		x.play();
  		img.addEventListener('click',changeAudio(x));
	}
	function changeAudio(x){
		return function(){
			x.pause();
			x.src = "sound2.mp3";
			x.play();
		}
	}
<h1 class="underline-on-hover" onclick="playAudio()" onmouseover="" cursor: pointer;">Test.</h1>
<img onmouseover="" style="cursor: pointer;" id="img"
	class="img-responsive" src="imagetest.png" alt="Image Test">

答案 2 :(得分:0)

这是一个过于简单的代码:

var audio1 = document.getElementById("audio1"),
  audio2 = document.getElementById("audio2"),
  whoIsPlaying = null;

function clickOnH1() {

  if (whoIsPlaying != 'H1') {

    audio2.pause();
    audio1.play();
    whoIsPlaying = 'H1';
  }
}

function clickOnIMG() {

  if (whoIsPlaying != 'IMG') {

    audio1.pause();
    audio2.play();
    whoIsPlaying = 'IMG';
  }
}

clickOnH1函数应该进入H1标记的onclick属性,clickOnIMG函数应该进入IMG标记的onclick属性。