使用Web存储(LocalStorage或SessionStorage)来保存点喜欢按钮的状态。当用户单击喜欢按钮时,将其状态保存到Web存储中。在页面刷新时,检查Web存储中是否保存了喜欢按钮的状态。如果存在,则恢复该状态。
示例代码:
// 检查Web存储中是否保存了喜欢按钮的状态
if (localStorage.getItem('likeButtonState')) {
// 恢复喜欢按钮的状态
likeButton.classList.add('liked');
}
// 在单击喜欢按钮时保存状态到Web存储
likeButton.addEventListener('click', function() {
likeButton.classList.toggle('liked');
if (likeButton.classList.contains('liked')) {
localStorage.setItem('likeButtonState', 'liked');
} else {
localStorage.removeItem('likeButtonState');
}
});