隐藏 div 并存储本地存储以在页面刷新时不显示 div
Hide div and store local storage not to show div on page refresh
单击时我在 div 中有一个图像按钮 我想隐藏图像按钮并以某种方式存储到本地存储,以便在页面刷新时不再显示 div。
<div class="whatsapp"><a href="https://chat.whatsapp.com/........." target="_blank">
<img src="/img/whatsapp_group.png" alt="Whatsapp Join Button"><div class="whatsappbut">To Find Out MORE!</div></a></div>
我向您的 div 添加了一个 ID(id="img-btn"
),以便在脚本标记中使用它。如果到目前为止用户没有点击您的图像按钮,localStorage.getItem('img-btn-clicked')
将 return 为空,否则它将 return 'true'(正如我们在 saveClicked 函数中设置的那样)。
只需确保将脚本标签放在 body 标签结束之前(或者您可以 link 一个单独的 Javascript 文件)。
<body>
<div id="img-btn" class="whatsapp">
<a href="https://chat.whatsapp.com/........." target="_blank">
<img src="/img/whatsapp_group.png" alt="Whatsapp Join Button" />
<div class="whatsappbut">To Find Out MORE!</div></a>
</div>
<script>
checkImgBtnClicked();
function checkImgBtnClicked() {
const clicked = localStorage.getItem('img-btn-clicked'); // if this is not set it will return null
if (clicked) {
document.getElementById('img-btn').style.display = 'none'; // hides the img-btn
} else {
// add event listener for image button click(saveClicked function will be executed if user clicks on image button
document.getElementById('img-btn').addEventListener('click', saveClicked);
}
}
function saveClicked() {
// set a flag in local storage that image button is clicked
localStorage.setItem('img-btn-clicked', 'true');
document.getElementById('img-btn').style.display = 'none'; // hides the img-btn after it gets clicked
}
</script>
</body>
单击时我在 div 中有一个图像按钮 我想隐藏图像按钮并以某种方式存储到本地存储,以便在页面刷新时不再显示 div。
<div class="whatsapp"><a href="https://chat.whatsapp.com/........." target="_blank">
<img src="/img/whatsapp_group.png" alt="Whatsapp Join Button"><div class="whatsappbut">To Find Out MORE!</div></a></div>
我向您的 div 添加了一个 ID(id="img-btn"
),以便在脚本标记中使用它。如果到目前为止用户没有点击您的图像按钮,localStorage.getItem('img-btn-clicked')
将 return 为空,否则它将 return 'true'(正如我们在 saveClicked 函数中设置的那样)。
只需确保将脚本标签放在 body 标签结束之前(或者您可以 link 一个单独的 Javascript 文件)。
<body>
<div id="img-btn" class="whatsapp">
<a href="https://chat.whatsapp.com/........." target="_blank">
<img src="/img/whatsapp_group.png" alt="Whatsapp Join Button" />
<div class="whatsappbut">To Find Out MORE!</div></a>
</div>
<script>
checkImgBtnClicked();
function checkImgBtnClicked() {
const clicked = localStorage.getItem('img-btn-clicked'); // if this is not set it will return null
if (clicked) {
document.getElementById('img-btn').style.display = 'none'; // hides the img-btn
} else {
// add event listener for image button click(saveClicked function will be executed if user clicks on image button
document.getElementById('img-btn').addEventListener('click', saveClicked);
}
}
function saveClicked() {
// set a flag in local storage that image button is clicked
localStorage.setItem('img-btn-clicked', 'true');
document.getElementById('img-btn').style.display = 'none'; // hides the img-btn after it gets clicked
}
</script>
</body>