Javascript:点击图片

时间:2018-05-20 13:01:37

标签: javascript audio onclick

我希望在点击图片时播放音频,但出于某种原因,我的代码无效。

HTML

  <.img id="horse" src="kon.png".>

(两端没有圆点)

JS

prr = function() {
        var ryk = document.createElement("audio")
        ryk.src = "ya.mp3"
        document.body.appendChild(ryk)

    }
    var kon = document.getElementById("horse")
    kon.addEventListener("click", prr)

3 个答案:

答案 0 :(得分:0)

你的html中的

添加此代码

<audio id="yourSound" style="display:none;">
    <source src="ya.mp3" type="audio/ogg">  
</audio>

在你的js代码中添加这个

    yourSound = function () {
        document.getElementById('yourSound')[0].play();
    }

    document.getElementById("horse").on('click', function(){
        yourSound();
    });

答案 1 :(得分:0)

您必须添加自动播放属性。 每行后使用分号

  

ryk.autoplay =&#34; 自动播放&#34;

答案 2 :(得分:0)

只需将ryk.play()添加到prr函数,并在文档准备就绪时运行代码:

function prr() {
  var ryk = document.createElement( 'audio' );
  ryk.src = 'https://www.w3schools.com/tags/horse.mp3';
  document.body.appendChild( ryk );
  ryk.play()
}

document.addEventListener( 'DOMContentLoaded', function() {
  document.getElementById( 'horse' ).addEventListener( 'click', prr)
})
img {
  cursor: pointer
}
<img id="horse" src="http://www.thinkmaze.com/wp-content/uploads/Red_Button_ThinkMaze.jpg" width="300", height="200">

相关问题