前端开发localStorage本地存储-防换肤

安卓app前端开发工具
前端js开发工具
最新前端开发工具

本地存储变量b的值:

localStorage.setItem(“b”,”isaac”);

本地获取变量b的值:

localStorage.getItem(“b”);

本地清除b的值:

localStorage.removeItem(“b”);

另外,目前javascript使用非常多的json格式,如果希望存储在本地,
可以直接调用JSON.stringify()将其转为字符串。
读取出来后调用JSON.parse()将字符串转为json格式,如下所示:

var details = {author:”isaac”,”description”:”fresheggs”,”rating”:100};

storage.setItem(“details”,JSON.stringify(details));

details = JSON.parse(storage.getItem(“details”));html 代码

<!DOCTYPE html>
    <head lang=”en”>
        <meta charset=”UTF-8″ />
        <title></title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
            body {
                background-color: #000;
            }
            ul {
                width: 800px;
                margin: 100px auto;
            }
            li {
                list-style: none;
                float: left;
                width: 100px;
                height: 100px;
                line-height: 100px;
                text-align: center;
                border: 5px solid #fff;
                border-radius: 50%;
                margin: 0 10px;
            }
        </style>
    </head>
    <body>
        <ul>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </body>
    <script src=”//cdn.bootcss.com/jquery/2.2.4/jquery.min.js “></script>
    <script>
        var colors = [‘red’, ‘green’, ‘orange’, ‘lightblue’, ‘blue’]
        // var lis=document.querySelectorAll(‘li’);
        // for(var i=0;i<lis.length;i++){
        // lis[i].style.background=colors[i];
        // lis[i].index=i;
        // lis[i].onclick=function(){
        // document.body.style.background=colors[this.index];
        // /*将当前的颜色存储起来*/
        // localStorage.setItem(‘bgc’,colors[this.index]);
        // }
        //
        // /*当页面打开时,颜色是之前关闭前设置的颜色*/
        // window.onload=function(){
        // document.body.style.background=localStorage.getItem(‘bgc’);
        // }
        //
        // }
        var lis = $(‘ul li’)
        for (var i = 0; i < lis.length; i++) {
            lis.eq(i)
                .css(‘background’, colors[i])
                .text(colors[i])
        }
        $(‘li’).click(function() {
            var nth = $(this).index()
            $(‘body’).css(‘background’, colors[nth])
            localStorage.setItem(‘newBg’, colors[nth])
        })
        var bg = localStorage.getItem(‘newBg’)
        $(‘body’).css(‘background’, bg)
    </script>
</html>
轻量级前端开发工具
android前端开发工具
移动android前端开发工具
» 本文来自:前端开发者 » 《前端开发localStorage本地存储-防换肤》
» 本文链接地址:https://www.rokub.com/8092.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!