在脚本中设置默认卷

时间:2018-03-20 20:48:38

标签: javascript html

我有一个网站可以在加载时循环播放音乐,但声音太大了。我有一个滑动条来改变音乐音量,但是如何将它默认为滑块的25%?

WEBSITE

<audio id=music loop autoplay src="peep.mp3">
  <p>If you are reading this, it is because your browser does not support the audio element.</p>
</audio>
<input id="vol-control" type="range" min="0" max="100" step="1" oninput="SetVolume(this.value)" onchange="SetVolume(this.value)"></input>

<script>
    function SetVolume(val)
    {
        var player = document.getElementById('music');
        console.log('Before: ' + player.volume);
        player.volume = val / 100;
        console.log('After: ' + player.volume);
    }
</script>

3 个答案:

答案 0 :(得分:1)

只需创建一个设置音量的脚本:

var audio = document.getElementById("music");
audio.volume = 0.25;

答案 1 :(得分:0)

如果您使用audio标签,只需在Javascript中获取DOM节点并操纵volume属性

var audio = document.querySelector('audio');
// Getting
console.log(volume); // 1
// Setting
audio.volume = 0.5; // Reduce the Volume by Half

您设置的数字应该在0.01.0的范围内,其中0.0是最安静的,而1.0是最响亮的。

答案 2 :(得分:0)

  • input是一个Void元素,因此不需要关闭</input>
  • 您正在使用maxmin,也请使用value
  • 避免使用内联JavaScript。让你的逻辑远离你的标记。
  • 初始化您的功能,如setVolume()
  • 使用camelCase setVolume代替PascalCase SetVolume,因为它是普通函数,而不是方法,类或构造函数......

&#13;
&#13;
const audio = document.getElementById('audio'),
      input = document.getElementById('volume'),
      setVolume = () => audio.volume = input.value / 100;

input.addEventListener("input", setVolume);
setVolume();
&#13;
<audio id=audio loop autoplay src="//upload.wikimedia.org/wikipedia/en/4/45/ACDC_-_Back_In_Black-sample.ogg">Audio is not supported on your browser. Update it.</audio>

<input id=volume type=range min=0 max=100 value=25 step=1>
&#13;
&#13;
&#13;

我认为你也喜欢this example