我的音乐播放器中有一个自定义音量栏和静音按钮。静音很简单,但是我想在第二次点击按钮时返回之前的音量。
示例: 假设当前音量为 50%
。单击静音按钮会将其更改为 0
。再次单击它应该会返回 50%
.
这是我尝试的方法:
var music = document.getElementById('music');
var volumehead = document.getElementById('volume-head');
var volumebar = document.getElementById('volume-bar');
var mute = document.getElementById('mute');
mute.addEventListener("click", muteSound);
function muteSound(){
if(mute.classList.contains('not-muted')){
// Save current values before changing them
var lastHead = volumehead.style.marginLeft;
var lastVolume = music.volume;
// Change classname for appearance and next click
mute.className = "muted";
// Change values to 0
volumehead.style.marginLeft = "0px";
music.volume = 0;
} else {
// Change classname for appearance and next click
mute.className = "not-muted";
// Use saved values
volumehead.style.marginLeft = lastHead;
music.volume = lastVolume;
}
}
2 variables
保存处理程序位置和音量的值在 if-statement
范围内指定。 ,这意味着他们在 else-statement
中没有一个.
在语句之外声明它们意味着这些值将被0
“覆盖” .
有没有办法保存这些值并在下次单击按钮时使用它们?
<小时/>编辑(解决方案):
if-statement
的值分配给variables
,只能由 else-statement
使用如果variables
被声明在 function
之外 .
最佳答案
var music = document.getElementById('music');
var volumehead = document.getElementById('volume-head');
var volumebar = document.getElementById('volume-bar');
var mute = document.getElementById('mute');
var lastHead, lastVolume;
mute.addEventListener("click", muteSound);
function muteSound() {
if (mute.classList.contains('not-muted')) {
// Save current values before changing them
lastHead = volumehead.style.marginLeft;
lastVolume = music.volume;
// Change classname for appearance and next click
mute.className = "muted";
// Change values to 0
volumehead.style.marginLeft = "0px";
music.volume = 0;
} else {
// Change classname for appearance and next click
mute.className = "not-muted";
// Use saved values
volumehead.style.marginLeft = lastHead;
music.volume = lastVolume;
}
}
关于if else 语句中的 JavaScript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45464229/