如何将所有 html 元素字体大小保存到本地存储

How to save all html elements font size to localstorage

我正在研究字体辅助功能,其中给出了三个图标 "A-"、"A"、"A+" 以减小、设置为默认值并增加所有元素的字体大小 -页。应该保存更改,当用户再次访问或打开另一个页面时,应该呈现更改后的字体大小。 为了增加字体大小,我使用

$(document).on("click","#large",function(){
    console.log("descrease");
    $('*').each(function(){
    var k =  parseInt($(this).css('font-size')); 
    var redSize = k * 1.10 ; //here, you can give the percentage( now it is reduced to 90%)
        $(this).css('font-size',redSize);  
    }); 
});

减小字体

$(document).on("click","#small",function(){
    console.log("descrease");
    $('*').each(function(){
    var k =  parseInt($(this).css('font-size')); 
    var redSize = k * 0.90 ; //here, you can give the percentage( now it is reduced to 90%)
        $(this).css('font-size',redSize);  
    }); 
});

我正在将所有字体大小保存到文档中的本地存储,如下所示

var allFonts = [];
$('*').each(function(){
    var k =  parseInt($(this).css('font-size')); 
    /*var redSize = k * 1.10 ; //here, you can give the percentage( now it is reduced to 90%)
    $(this).css('font-size',redSize);*/  
    allFonts[$(this)] = k; 
    console.log(allFonts,"allFonts");
    localStorage.setItem("allFonts",allFonts);
});

将字体大小设置为默认值

$(document).on("click","#normal",function(){
    console.log("normal");
    var allElems = localStorage.getItem("allFonts");
    console.log(allElems);
    $(allElems).each(function(k,v){
        console.log(k);
        $(k).css("font-size",v)  // Not working
    });
});

但是localStorage中的字体大小没有正确保存。我试图检查 "allFonts" 的值,它是在文档就绪时生成的。显示为

[[object Object]: 14]
[object Object]: 14
length: 0
__proto__: Array(0)

请告诉我正确的方法。谢谢。

localStorage 存储 字符串 ,而不是数组。要在 localStorage 中存储结构化数据(如数组),请使用 JSON:

localStorage.setItem("allFonts", JSON.stringify(allFonts));

...和

allFonts = JSON.parse(localStorage.getItem("allFonts")) || [];

|| [] 的原因是,当您调用 getItem 而该项目不存在时,您会返回 null。如果将 null 传递给 JSON.parse,它会被转换为字符串 "null"(因为 parse 需要一个字符串),然后解析为 null,这就是return JSON.parse 的值。 || [] 在这种情况下给你一个空白数组。也可以这样写:

allFonts = JSON.parse(localStorage.getItem("allFonts") || "[]");

设置所有字体:localStorage.setItem("allFonts", JSON.stringify(allFonts)); 检索:allFonts = JSON.parse(localStorage.getItem("allFonts"))