第一次访问时显示一条消息(如cookie同意)



我正在构建一个网站,并试图在页面顶部(页眉内)显示一条消息,因此它在每次访问/会话中只显示一次。例如,本网站顶部的"预约"绿色栏:https://www.tiffany.co.uk

我的网站在这里:https://vitrify.tempurl.host/

我已经出现了一条消息(页面顶部的橙色面板),但目前每次加载页面时都会出现。我只想让它出现一次,就像饼干一样。

我花了几个小时寻找解决方案,但由于我不是程序员,我正在苦苦挣扎。任何帮助都将不胜感激。

这是HTML:

function myFunction() {
var x = document.getElementById("topDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
.topDIV {
color: #000000;
font-weight: 300;
font-size: 15px;
}
.topDIV a:link, .topDIV a:visited {
color: #000000!important;
font-weight: 500;
letter-spacing: -0.3px;
line-height: 1.2        ;
}
span.topDIV {
}
.topDIV a:hover {
border-bottom: 1px solid rgba(0,0,0,0.50) !important;
display: inline-block;
}
.button-x {
position: relative;
float: right;
top: -5px;
background:none; 
border:none; 
color:rgb(0,0,0) ;
cursor: pointer; 
vertical-align: 0px;
}
.button-x:before {
font-family: 'Times';
content: "X";
font-size:30px;
vertical-align:0px;
opacity:0.5;
}
.button-x:hover {
opacity:1!important;
}
<span class = "topDIV">Welcome to <em>Vitrify</em>. Following in the finest traditions of vitreous enamelled jewellery. <a href = "#">Find&nbsp;out&nbsp;more.</a></span><button class = "button-x" onclick="myFunction()"></button>

如上所述,您需要使用localStorage来解决您的问题。

  • 需要知道页面何时加载
  • localStorage获取值
  • 将事件添加到按钮(我从html中删除了onclick事件以获得更干净的解决方案)
  • 单击为localStorage设置值并隐藏项目后
  • 如果localStorage有值,则隐藏元素

工作示例

Javascript

document.addEventListener('DOMContentLoaded', function () {
const topDiv = document.querySelector('.topDIV');
const buttonX = document.querySelector('.button-x');
// Get value from localStorage when open the page
const lS = localStorage.getItem('first-visit');
// Add button 'click' event
buttonX.addEventListener('click', () => {
// Set value to the localStorage
localStorage.setItem('first-visit', false);
// hide DOM element
topDiv.style.display = 'none';
});
// This does not check on the first visit to the page
// If localStorage have value, hide DOM element
if (lS) topDiv.style.display = 'none';
});

Html

<span class="topDIV"
>Welcome to <em>Vitrify</em>.Following in the finest traditions of
vitreous enamelled jewellery.
<a href="#">Find out more.</a>
</span>
<button class="button-x"></button>

您可以添加一个标志"showTopMessage:true";在您的本地存储或会话存储中,基于用户的一次消息或每次访问。分别地

在交叉/关闭图标上点击设置标志";showTopMessage:false";。

const showTopBar = "SHOW_TOP_BAR"; 
const[showTopBar,setShowTopBar] = useState(true);
useEffect(()=>{
const saveState = localstorage.getItems(showTopBar);
if(saveState) setShowTopBar(saveState);
else localstorage.setItem(showTopBar, true);
},[]);
const handleTopBarClose = () => {
setShowTopBar(false);
localstorage.setItem(showTopBar, false);
}

return(
<div>
{
showTopBar && <TopBarComponent onClose={handleTopBarClose}/>
}
</div>
)

最新更新