首页 > 解决方案 > 如何将所有html元素字体大小保存到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)

请建议我正确的方法。谢谢。

标签: javascripthtmlcssfonts

解决方案


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


推荐阅读