简体   繁体   English

如何在本地存储或用户设置的cookie中实现数据存储?

[英]How to implement a data storage in local storage or in cookie set by users?

I have three scripts through which a user can change CSS on a page by selecting a .css file:我有三个脚本,用户可以通过这些脚本通过选择.css文件来更改页面上的 CSS:

<script>
function setStyle(css) {
  document.querySelector('link#style').href = css;
}
</script>

Changes the font size:更改字体大小:

<script>
$(document).ready(function () {

  //Минимальный размер шрифта
  var min=9;    

  //Максимальный размер шрифта
  var max=16;   

  //Сохраняем заданное в таблице стилей значение размера шрифта
  var reset = $('p').css('fontSize'); 

  //Изменение размера будет проводиться для указанных элементов
  var elm = $('p, h1, a, ul, li, div.sp-head, h2.widgettitle, label, h3.comment-reply-title, input.submit, span, h4.comments');  

  //Устанавливаем в переменной значение шрифта по умолчанию (удаляем px)
  var size = str_replace(reset, 'px', ''); 
  var size_reset = size;

  //Функция увеличения размера шрифта
  $('a.fontSizePlus').click(function() {

    //Если размер шрифта меньше или равен максимальному значению
    if (size<=max) {

      //Увеличиваем размер шрифта
      size++;

      //Устанавливаем размер шрифта
      elm.css({'fontSize' : size});
    }

    //Прерываем передачу события далее по дереву DOM
    return false;   

  });

  //Функция уменьшения размера шрифта
  $('a.fontSizeMinus').click(function() {

    //Если размер шрифта больше или равен минимальному значению
    if (size>=min) {

      //Уменьшаем размер
      size--;

      //Устанавливаем размер шрифта
      elm.css({'fontSize' : size});
    }

    //Прерываем дальнейшую передачу события по дереву DOM
    return false;   

  });

  //Функция сброса к значению по умолчанию
  $('a.fontReset').click(function () {

    //Устанавливаем значение размера шрифта по умолчанию
     size = size_reset;
     elm.css({'fontSize' : reset});     
  });

});

//Функция замена строки
function str_replace(haystack, needle, replacement) {
  var temp = haystack.split(needle);
  return temp.join(replacement);
}
</script>

Extends content page:扩展内容页面:

<script type="text/javascript">
window.onload = function() {
    document.getElementById('WideButton').onclick = function()
    {
        if(document.body.className != 'wide_class')
        {
            document.body.className = 'wide_class';
        }
        else
        {
            document.body.className = '';
        }
    }
}
</script>

Management is done through link elements:管理是通过链接元素完成的:

<a href="#" class="fontSizePlus">A+</a> | <a href="#" class="fontSizeMinus">A-</a>
<a id="WideButton" name="WideButton">Wide mode</a>

<a onclick="setStyle('sitecom/wp-content/themes/theme1/style1.css')" href="#">style1</a> 
<a onclick="setStyle('sitecom/wp-content/themes/theme1/style2.css')" href="#">style2</a>
<a onclick="setStyle('sitecom/wp-content/themes/theme1/style3.css')" href="#">style3</a>
<a onclick="setStyle('sitecom/wp-content/themes/theme/style4.css')" href="#">style4</a>

The style itself is set in:样式本身设置为:

<link id="style" href="sitecom/wp-content/themes/theme1/style1.css" rel="stylesheet">

On the page, all of these changes work fine.在页面上,所有这些更改都可以正常工作。 But if you follow the link or refresh the page, everything goes astray.但是,如果您点击链接或刷新页面,一切都会误入歧途。 How to make changes to the site by the user stored in cookies or in local storage?存储在 cookies 或本地存储中的用户如何更改站点? So, that after reloading CSS the page properties do not get off?那么,重新加载 CSS 后页面属性没有下车?

You can use the localstorage api and store the user selected css styles in the form of a json when user is updating the styles. You can use the localstorage api and store the user selected css styles in the form of a json when user is updating the styles. And in the $(document).ready u can check whether localstorage has any user selected style preferences then load those styles or else load default styles as your are currently doing.$(document).ready中,您可以检查 localstorage 是否有任何用户选择的样式首选项,然后加载那些 styles 或加载默认的 styles,就像您当前所做的那样。

As example of how you might do this style-switching using localStorage rather than a cookie to remember the user preference I quickly hashed together a little demo.作为如何使用localStorage而不是cookie来记住用户偏好的style-switching的示例,我快速地整理了一个小演示。

StoreFactory is just a littler helper function I put together and use to simplify some of the workings of local/session storage ( though, tbh, it's pretty simple already. ) It appears to work OK in tests - you will need to modify from console.info( data ) onwards to actually set the active stylesheet - I don't have stylesheets 1,2,3 and 4 available.... StoreFactory只是一个小帮手 function 我放在一起并使用它来简化本地/会话存储的一些工作(虽然,tbh,它已经很简单了。)它在测试中似乎工作正常 - 您需要从console.info( data )开始实际设置活动样式表 - 我没有可用的样式表1,2,3 and 4 ....

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Stylesheet switcher</title>
        <link rel='stylesheet' id='style' />
        <script>

            const StoreFactory=function( name, type ){
                'use strict';
                const engine = !type || type.toLowerCase() === 'local' ? localStorage : sessionStorage;

                const set=function( data ){
                    engine.setItem( name, JSON.stringify( data ) );
                };
                const get=function(){
                    return exists( name ) ? JSON.parse( engine.getItem( name ) ) : false;
                };
                const remove=function(){
                    engine.removeItem( name );
                };
                const exists=function(){
                    return engine.getItem( name )==null ? false : true;
                };
                const create=function(){
                    if( !exists() ) set( arguments[0] || {} );
                };
                return Object.freeze({
                    set,
                    get,
                    exists,
                    create,
                    remove
                });
            };




            let store;
            let sheet=document.querySelector('link#style');


            const setStyle=function( css ){
                store.create();
                store.set({css:css});
                sheet.href = css;
            };


            window.onload = function(){
                store=new StoreFactory( 'css', 'local' );
                if( store.exists() ){
                    let data=store.get();
                    console.info( data );

                    /* to call the stylesheet */
                    sheet.href=data.css;
                }
            };

        </script>
    </head>
    <body>


        <a href="#" class="fontSizePlus">A+</a> | <a href="#" class="fontSizeMinus">A-</a>
        <a id="WideButton" name="WideButton">Wide mode</a>

        <a onclick="setStyle('sitecom/wp-content/themes/theme1/style1.css')" href="#">style1</a> 
        <a onclick="setStyle('sitecom/wp-content/themes/theme1/style2.css')" href="#">style2</a>
        <a onclick="setStyle('sitecom/wp-content/themes/theme1/style3.css')" href="#">style3</a>
        <a onclick="setStyle('sitecom/wp-content/themes/theme/style4.css')" href="#">style4</a>


    </body>
</html>

Working example工作示例

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Stylesheet switcher</title>
        <link rel='stylesheet' id='style' />
        <script>

            const StoreFactory=function( name, type ){
                'use strict';
                const engine = !type || type.toLowerCase() === 'local' ? localStorage : sessionStorage;

                const set=function( data ){
                    engine.setItem( name, JSON.stringify( data ) );
                };
                const get=function(){
                    return exists( name ) ? JSON.parse( engine.getItem( name ) ) : false;
                };
                const remove=function(){
                    engine.removeItem( name );
                };
                const exists=function(){
                    return engine.getItem( name )==null ? false : true;
                };
                const create=function(){
                    if( !exists() ) set( arguments[0] || {} );
                };
                return Object.freeze({
                    set,
                    get,
                    exists,
                    create,
                    remove
                });
            };




            let store;
            let sheet=document.querySelector('link#style');


            const setStyle=function( css ){
                store.create();
                store.set({css:css});
                sheet.href = css;
            };


            window.onload = function(){
                store=new StoreFactory( 'css', 'local' );
                if( store.exists() ){
                    let data=store.get();
                    console.info( data );

                    /* to call the stylesheet */
                    sheet.href=data.css;
                }
            };
        </script>
    </head>
    <body>


        <a href="#" class="fontSizePlus">A+</a> | <a href="#" class="fontSizeMinus">A-</a>
        <a id="WideButton" name="WideButton">Wide mode</a>

        <a onclick="setStyle('style1.css')" href="#">style1</a> 
        <a onclick="setStyle('style2.css')" href="#">style2</a>
        <a onclick="setStyle('style3.css')" href="#">style3</a>
        <a onclick="setStyle('style4.css')" href="#">style4</a>


    </body>
</html>

The stylesheets used使用的样式表

/* style1.css */
body{background:red;color:white}

/* style2.css */
body{background:blue;color:white}

/* style2.css */
body{background:blue;color:white}

/* style4.css */
body{background:green;color:yellow}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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