为网站中的静音/取消静音设置 cookie
Posted
技术标签:
【中文标题】为网站中的静音/取消静音设置 cookie【英文标题】:Set cookie for mute/unmute sound in website 【发布时间】:2021-06-06 05:29:36 【问题描述】:我需要帮助才能关闭和打开网站上按钮的声音。我无法通过按下切换开关打开和关闭并通过 localStorage 或 Cookies 存储它来做到这一点。如果有人知道如何解决它,我将不胜感激。 Т谢谢!
<div class="setting">
<input class="sound-toggle" type="checkbox" id="sound-toggle" />
<label for="sound-toggle">Звук</label>
</div>
<audio id="audio" src="audio/tap.mp3"></audio>
JS
$("audio").prop('muted', false);
$(".sound-toggle").click( function ()
if( $("audio").prop('muted') )
$("audio").prop('muted', false);
else
$("audio").prop('muted', true);
);
【问题讨论】:
【参考方案1】:我就是这样做的:https://github.com/gregor-dev-443/gregor-dev-443.github.io/blob/main/buttontapsoundstest.html. 您可以在https://gregor-dev-443.github.io/buttontapsoundstest.html 试用。 注意:声音需要一些时间才能加载,因此不会立即生效。 我无法使用嵌入式 sn-p,因为它们不允许使用本地存储。
编辑链接现在失效了,这是代码:
<!DOCTYPE html>
<html>
<head>
<title>Test for button tap sounds</title>
<meta charset="utf-8" />
</head>
<body>
<h1>Test for button tap sounds</h1>
<p>
<input type="checkbox" id="mute-checkbox" check />
<label for="mute-checkbox">Mute</label>
</p>
<p>
<button id="test-button">Test</button>
</p>
<audio id="tap-sound" src="https://opengameart.org/sites/default/files/Menu%20Selection%20Click.wav"></audio>
<script>
//Store the HTML elements in variables
const muteCheckbox = document.getElementById("mute-checkbox");
const tapSound = document.getElementById("tap-sound");
const testButton = document.getElementById("test-button");
//Automatically enable the checkbox when the item "muted" is present in local storage
if (localStorage.getItem("muted"))
muteCheckbox.checked = true;
//Add the item "muted" to local storage when the checkbox is enabled and remove the item when it isn't enabled anymore
muteCheckbox.addEventListener("change", () =>
if (muteCheckbox.checked)
localStorage.setItem("muted", "on");
else
localStorage.removeItem("muted");
);
//Play the sound when the button is clicked and the item "muted" isn't present in local storage
testButton.addEventListener("click", () =>
if (!localStorage.getItem("muted"))
tapSound.play();
);
</script>
</body>
</html>
【讨论】:
以上是关于为网站中的静音/取消静音设置 cookie的主要内容,如果未能解决你的问题,请参考以下文章