我有一个网站可以在加载时循环播放音乐,但声音太大了。我有一个滑动条来改变音乐音量,但是如何将它默认为滑块的25%?
<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>
答案 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.0
到1.0
的范围内,其中0.0
是最安静的,而1.0
是最响亮的。
答案 2 :(得分:0)
input
是一个Void元素,因此不需要关闭</input>
max
,min
,也请使用value
。 setVolume()
setVolume
代替PascalCase SetVolume
,因为它是普通函数,而不是方法,类或构造函数......
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;
我认为你也喜欢this example。