如何确保具有两个不同功能的会话存储不会相互干扰?



我写了一个简单的jquery脚本,它为页面上的每个元素增加了一定的百分比font-size。我设法将其结果保存在sessionStorage中,因此刷新页面后,我保存了脚本的结果。当我添加第二个脚本时,font-size增加另一个值时,会出现此问题。我使用了与第一个脚本相同的方法来将值保存在 sessionStorage 中,但不幸的是,两者一起使用并不能正常工作。保存第一个脚本的值时,我运行第二个脚本,然后刷新页面,然后保存第一个脚本的结果。如何让两者协同工作而不发生碰撞?

JQuery 代码:

$('.normal-size').click(function(){
$('html').each(function(){
$(this).css("fontSize", "100%");
});
});
const biggerFontSize = sessionStorage.getItem("biggerFonts");
if(biggerFontSize == "true"){
sessionStorage.removeItem("largestFonts");
$('html').each(function(){
$(this).css("fontSize", "125%");
});
}
$('.bigger-size').click(function(){
$('html').each(function(){
$(this).css("fontSize", "125%");
sessionStorage.setItem("biggerFonts", "true");
});
});
const largestFontSize = sessionStorage.getItem("largestFonts");
if(largestFontSize == "true"){
sessionStorage.removeItem("biggerFonts");
$('html').each(function(){
$(this).css("fontSize", "150%");
});
}
$('.largest-size').click(function(){
$('html').each(function(){
$(this).css("fontSize", "150%");
sessionStorage.setItem("largestFonts", "true");
});
});

我的小提琴: https://jsfiddle.net/nsog8sm43x/9zfnep4d/3/

使用单个键进行fontSize,使用单个函数设置字体大小。然后,您的按钮逻辑变得非常简单,页面加载时字体大小的初始设置也是如此。

function setFontSize(size) {
if (size != null && size.length) {
sessionStorage.setItem("fontSize", size);
$('html').each(function() {
$(this).css("fontSize", size);
});
}
}
// on page load, get the font size from sessionStorage and set it
const fontSize = sessionStorage.getItem("fontSize");
setFontSize(fontSize);
$('.normal-size').click(function() {
setFontSize("100%");
});
$('.bigger-size').click(function() {
setFontSize("125%");
});
$('.largest-size').click(function() {
setFontSize("150%");
});

这是一个更新的jsFiddle。

您需要添加单会话存储密钥以根据您的选择更新值,如下所示。

const fontSize = sessionStorage.getItem("fontSize");

if (fontSize == "normal") {
$('html').each(function() {
$(this).css("fontSize", "100%");
});
}
$('.normal-size').click(function() {
sessionStorage.setItem("fontSize", "normal");
$('html').each(function() {
$(this).css("fontSize", "100%");
});
});
if (fontSize == "bigger") {
$('html').each(function() {
$(this).css("fontSize", "125%");
});
}
$('.bigger-size').click(function() {
sessionStorage.setItem("fontSize", "bigger");
$('html').each(function() {
$(this).css("fontSize", "125%");
});
});
if (fontSize == "larger") {
$('html').each(function() {
$(this).css("fontSize", "150%");
});
}
$('.largest-size').click(function() {
sessionStorage.setItem("fontSize", "larger");
$('html').each(function() {
$(this).css("fontSize", "150%");
});
});

最新更新