toggleClass保存在Cookie或localStorag

toggleClass保存在Cookie或localStorag

本文介绍了jQuery将toggleClass保存在Cookie或localStorage中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图保存cookie或使用 localStorage (以更好的为准)来记住访客何时单击加号按钮以显示/隐藏div.谁能协助使以下代码与Cookie或 localStorage 一起使用?

I am trying to save a cookie or use localStorage (whichever is better) to remember when a visitor has clicked on a plus button to show/hide a div. Can anyone assist in helping make the below code work with a cookie or localStorage?

$('.plus').on('click', function(e) {
    $(".plus .icon .two").toggleClass('horizontal');
    $(".welcome-section").toggleClass('open');
    $(".welcome-header p").toggleClass('explore');
});

推荐答案

我更喜欢使用本地存储:

Javascript:

var $content = $('.js-content');

if (localStorage.getItem('isVisible') === 'true') {
    $content.addClass('content_visible');
}

$('.js-button').on('click', function() {
    $content.toggleClass('content_visible');
    localStorage.setItem('isVisible', $content.hasClass('content_visible'));
});

CSS:

.content {
    display: none;
}

    .content_visible {
        display: block;
    }

HTML:

<button type="button" class="js-button">+</button>
<div class="content js-content">This is content</div>

JSFiddle

这篇关于jQuery将toggleClass保存在Cookie或localStorage中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 20:16