简体   繁体   中英

How to “save” my JS Change in LocalStorage

I need when the visitor chooses one, This change is saved in the localStorage, but I do not know how to do it. I've tried a lot by looking at examples on the internet but none fit my case and I got lost. here's my code:

$(document).ready(function(){

    // better body background color changing function
    $('.menu-thing').click(function(){
        $('body').removeClass('whoa4'); 
        $('.face4.two4').removeClass('visible17');
        $('#wrap').css('background-color', $(this).css('background-color')); 
        return false;
    });

    $('.whoa-button4').click(function(){
        $('body').toggleClass('whoa4'); 
        $('.face4.two4').toggleClass('visible17');
        return false;
    });

});

Here is the working html:

<!DOCTYPE html>
<html>
<head>
<script src="../libraries/jquery-3.1.1.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="menuStyles.css">
</head>
<body>
<input type="checkbox" id="menuCheckbox"/>
<div class="menu-container">
    <label class="menu-label" for="menuCheckbox">
        <div class="white-line"></div>
    </label>
    <div class="menu-thing side one">:D</div>
    <div class="menu-thing side two">( ._.)</div>
    <div class="menu-thing side three">n_n</div>
    <div class="menu-thing side four">:)</div>
</div>
<div class="face"></div>
<div class="face two"></div>
<div class="whoa-button">:O</div>
</body>
</html>

I reworked this locally to ensure it is working. This is the javascript.

$(function(){

$('body').css('background-color', loadBG); 

$('.menu-thing').click(function(){
$('body').removeClass('whoa'); 
$('.face.two').removeClass('visible');
$('body').css('background-color', $(this).css('background-color')); 
setStorage('bgColor', $(this).css('background-color'));
return false;
});

$('.whoa-button').click(function(){
$('body').toggleClass('whoa'); 
$('.face.two').toggleClass('visible');
return false;
});

function loadBG(){
    var bgColor = getStorage('bgColor');
    if (bgColor != "none"){
        return bgColor;
    } else {
        var currentColor = $('body').css('background-color');
        return currentColor;
    }
}

function setStorage(key,info) {
localStorage.setItem(key, JSON.stringify(info));
}

function getStorage(key) {
var item = localStorage.getItem(key);
if(item != "undefined" && item != null){
    return JSON.parse(item);
} else {
    return "none";
}
}
});

I did verify it saves the bg color in local storage after each click.It uses the css you provided in the fiddle. of note(!) I did reference jquery because you were using jquery syntax and you'll have to rename the .css file to what you desire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM