jQuery: On click on native audio element

时光总嘲笑我的痴心妄想 提交于 2019-12-24 05:46:07

问题


How can you detect a click on the native browser's audio element with jQuery?

Doesn't seem to work in Chrome.

$('audio').click(function(){
    alert("You clicked on some audio player");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<audio preload="none" src="http://webaudioapi.com/samples/audio-tag/chrono.mp3" type="audio/mpeg" controls=""></audio> 

http://codepen.io/Subfader/pen/GqrmNQ


回答1:


You are correct in saying that it doesn't seem to be able to call the native audio tag in the usual way, neither using vanilla js nor jquery. I tried using a class (which i thought would be successful) but to no avail.

However, that said I think I have a solution to your overall problem. Try out the below snippet. When one player is selected, the others stop. (only one plays at a time).

You could extend this by perhaps adding a visible class when playing an making the visibility set to hidden or display:none by default (but actually then how would you click play? - hmmm) Anyway, point is, customise as you wish.

hope this helps

$("audio").each(function(index) {
  var num = index+1;
  $(this).attr('id','myaudio' + num);
});

document.addEventListener('play', function(e){
    var aplayers = $('audio');
    var leng = $('audio').length;
    //console.log(leng);
    for(var i = 0; i < leng;i++){
        if (aplayers[i] != e.target){
            aplayers[i].pause();
        }
    }
}, true);
audio{margin-bottom:10px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id=' '  controls src="http://www.soundjay.com//mechanical/gun-cocking-01.mp3">
</audio>

<audio id=' ' src="http://www.rachelgallen.com/monkey.mp3" controls>
</audio>

<audio preload="none" src="http://webaudioapi.com/samples/audio-tag/chrono.mp3" type="audio/mpeg" controls=""></audio>



回答2:


It doesn't look like it works with even using plain JavaScript in Chrome. I would suggest that you wrap your <audio> element in a div and place the click event on that element instead.

Or depending on what you're trying to accomplish, you could bind to other Media events such as play, pause or seek.



来源:https://stackoverflow.com/questions/38282774/jquery-on-click-on-native-audio-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!