在脚本中设置默认卷

问题描述 投票:0回答:3

我有一个网站可以在加载时循环播放音乐,但它太响了。我有一个滑块来改变音乐音量,但我如何将其默认为滑块的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>
javascript html
3个回答
1
投票

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

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

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是最响亮的。


0
投票
  • input是一个Void元素,因此不需要关闭</input>
  • 你正在使用maxmin,好吧,也使用value
  • 避免使用内联JavaScript。让你的逻辑远离你的标记。
  • setVolume()一样初始化你的功能
  • 使用camelCase setVolume而不是PascalCase SetVolume,因为它是一个普通函数,而不是Method,Class或构造函数......

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

input.addEventListener("input", setVolume);
setVolume();
<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>

我想你也喜欢this example

© www.soinside.com 2019 - 2024. All rights reserved.