Javascript 不更新样式

标签 javascript html css

为什么这行不通? localStorage.fontSize包含正确的值,但第一个 document.body.style.fontSize = localStorage.fontSize + "pt";不更新样式。

<script type="text/javascript">

if(!localStorage.fontSize){
    localStorage.fontSize = Number(11); 
}
else{
    document.body.style.fontSize = localStorage.fontSize + "pt"; /* This row doesnt run */
}

function resetFont(){
    localStorage.fontSize = Number(11);
    document.body.style.fontSize = "11pt";
}
function enlargeFont(){
    localStorage.fontSize++;
    document.body.style.fontSize = localStorage.fontSize + "pt"; /* But this does if called */
}

</script>

请不要使用 jQuery 片段。

最佳答案

似乎 document.body 在代码运行时不存在。将代码移动到 body 标记的开头或结尾。

参见 Why does jQuery or a DOM method such as getElementById not find the element? , 基本相同。

关于Javascript 不更新样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16906939/

相关文章:

javascript - Bootstrap 4 工具提示卡住使用 Datatables.net

javascript - 将正则表达式中的组标记为可选

javascript - 粘性导航栏 - 不起作用

javascript - ionic 2 : similar $ionicSlideBoxDelegate service?

javascript - 如何创建具有重叠 View 的轮播? [包含 jsFiddle 和 ASCII 艺术}

html - 如何调整选择下拉高度

javascript - 在 HTML 区域标记中使用图像

javascript - 使用 js 和 underscore.js 显示代码时出现问题

javascript - 切换按钮时保留滚动位置

html - CSS 在两个 Div 中的奇怪行为