我有一个问题,让我的网站记住按下按钮。网站自动播放音乐,它有静音按钮,但是当你转到下一页或刷新页面时,它不记得你是否按下了按钮。该本地存储脚本似乎无法正常工作。
function mute(){
var audio = document.getElementById("music")
var toggle = document.getElementById("toggle")
if (audio.muted == true) {
audio.muted=false
toggle.innerHTML ="MUTE"
} else {
audio.muted=true
toggle.innerHTML ="UNMUTE"
}
}

<audio id="music" autoplay loop>
<source src="/files/music.mp3" type="audio/mpeg">
<source src="/files/music.ogg" type="audio/ogg"> Your browser does not support the audio element.
</audio>
<script>
var audio = document.getElementById("music");
audio.volume = 0.3;
</script>
<button id="toggle" class="toggle" onclick="mute()">MUTE</button>
<script>
localStorage.setItem('toggle', 'true');
localStorage.getItem('toggle'); // returns 'true'
</script>
&#13;
答案 0 :(得分:0)
每次页面刷新时,您的原始脚本都会将'toggle'
设置为true
。
这应该按预期工作,请参阅JSFiddle(点击按钮确认它正确存储值后再次按Run
):https://jsfiddle.net/kevinkassimo/m44vh2qy/
(由于代码段沙盒环境,以下代码无效)&#39;
<button id="toggle" class="toggle" onclick="toggle()">TOGGLE</button>
<h1 id="txt"></h1>
<script>
function toggle() {
let isToggle = +localStorage.getItem('toggle');
if (!isToggle) {
localStorage.setItem('toggle', 1);
document.getElementById('txt').innerHTML = 'Toggled';
} else {
localStorage.setItem('toggle', 0);
document.getElementById('txt').innerHTML = 'Not Toggled';
}
}
document.addEventListener("DOMContentLoaded", function(event) {
if (+localStorage.getItem('toggle')) {
document.getElementById('txt').innerHTML = 'Toggled';
} else {
document.getElementById('txt').innerHTML = 'Not Toggled';
}
})
</script>
&#13;
答案 1 :(得分:0)
您的IF语句检查布尔值为TRUE,但您的本地存储变量设置为字符串“true”