gpt4 book ai didi

javascript - 如何在本地存储中保存字体大小?

转载 作者:行者123 更新时间:2023-11-28 03:01:20 25 4
gpt4 key购买 nike

/* The code that actually changes the font size */

function fontSize(selectTag) {
var listValue = selectTag.options[selectTag.selectedIndex].text;
document.getElementById("text").style.fontSize = listValue;
}

/*my failed text to try and save the font size*/

function onClick(){
var button = document.getElementById('button');
button.addEventListener("click", save, false);
display();
}
function saveFont(){
localStorage.setItem();
}

window.addEventListener("load", onClick, false);
  
<!-- This is how they choose their font size -->
<select onchange="fontSize(this);" size="11">
<option>xx-small</option>
<option>x-small</option>
<option>small</option>
<option>medium</option>
<option>large</option>
<option>x-large</option>
<option>xx-large</option>
<option>100%</option>
<option>250%</option>
<option>2cm</option>
<option>100px</option>
</select>
<br>
<!-- this is how i would save it since they don't physically click a button -->
<input type="button" id="save" value="Save Font Size">


<!-- The body tag is has an 'id="text' "-->

所以更改字体大小不是问题,我已经记下了。但是对于我来说,我无法将它保存到 HTML 本地存储中,因此当我更改页面或刷新时,字体大小与我更改后的大小保持不变。任何帮助将不胜感激。

最佳答案

重要的是,当您尝试获取 CSS 属性值时,您将获得元素属性的最终计算值。有些属性不是在元素的 style 属性上设置的,而是通过 CSS 类或其他选择器设置的。在这些情况下,尝试使用 element.style 获取此类属性将产生一个空字符串。为确保获得最终值,请使用 window.getComputedStyle() .

接下来,要获取元素并将其设置到 localStorage,您可以使用 localStorage.setItem(key, value) localStorage.getItem(key) API。您的代码是:

localStorage.setItem();

它不传递键名或值,因此不会设置任何内容。以下是设置和获取 localStorage 值的写法:

将字体大小设置为 localStorage:

localStorage.setItem("font", window.getComputedStyle(DOMelementInQuestion).fontSize);

恢复字体大小:

var storedFont = localStorage.getItem("font");

关于javascript - 如何在本地存储中保存字体大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46184895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com