页面加载后触发单击功能

时间:2016-02-14 12:14:22

标签: javascript jquery html5 events triggers

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
  $('#play')[0].click();//initial click on 'play' button to play music which doesn't seem to be working...
  $('#play').on('click',function(){
    $("#Audio1")[0].play();
})
});
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <audio id="Audio1" controls="controls" 
src="http://themes.rascals.eu/eprom/dark/wp-content/uploads/2012/11/Madoff-Bomp.mp3" type="audio/mp3" >
</audio>
 HTML5 Audio is required for this example. 

<input type="button" id="play" value="play" />


</body>
</html>

我想在“播放”按钮上触发点击事件以播放音乐。

我需要这样做,因为'自动播放'不适用于移动设备。

由于数据问题,默认情况下会被阻止。

我发现这篇文章http://makandracards.com/makandra/13893-autoplay-html5-audio-in-chrome-for-android-mobile-safari-in-ios,结果证明他是对的,好像我在手机上点按了这个播放按钮,音乐按预期播放。

我希望在页面加载后触发此按钮被单击。它没有用,但是如果我运行相同的js IN CONSOLE它就可以了。

编辑1

根据评论中给出的建议我已尝试过但仍然没有运气。

$(document).ready(function() {
  $('#play').on('click', function() {
    $("#Audio1")[0].play();
  })
  $('#play')[0].click(); //initial click on 'play' button to play music which doesn't seem to be working...
});

1 个答案:

答案 0 :(得分:0)

您需要在点击操作之前注册点击事件:

<audio>

修改

问题不在于您的点击操作。 Click事件按预期工作,但Apple已经专门禁用了自动播放,直到用户通过用户操作(用户点击播放按钮)启动它,如文章中所述:

Safari HTML5 Audio and Video Guide

如果您对paused元素进行输出,则会在呈现时看到<audio>的{​​{1}}属性自动设置为'true'。< / p>

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#play').on('click',function(event){
            $("#Audio1")[0].play();

            var myplay = document.getElementById('Audio1');
            var log = document.getElementById('screenlog');
            for (var prop in myplay) {
                log.innerHTML += prop + ":" + myplay[prop] + "<br>";
            }
        });
        $('#play')[0].click();

        });
    </script>
    <meta charset=utf-8 />
    <title>JS Bin</title>
</head>
<body>
<audio id="Audio1" controls="controls"
       src="http://themes.rascals.eu/eprom/dark/wp-content/uploads/2012/11/Madoff-Bomp.mp3" type="audio/mp3" >
</audio>
HTML5 Audio is required for this example.
<div id="screenlog"></div>
<input type="button" id="play" value="play" />


</body>
</html>