如何使用JavaScript在HTML页面间传递CSS样式值
问题分析
你遇到的核心问题有三个:
- localStorage仅支持存储字符串:直接把DOM元素存入localStorage,会被自动转换为字符串
[object HTMLDivElement],这就是第二个页面圆圈内显示这段文本的原因。 - 重复ID冲突:第二个页面同时存在
<div id="first">和<span id="first">,HTML中ID必须唯一,会导致getElementById只能获取第一个元素,逻辑混乱。 - 无需传递整个DOM元素:两个页面的圆圈样式完全一致,只需同步颜色状态即可,不需要传递整个元素。
解决方案
修改第一个页面代码
只将圆圈的当前颜色存入localStorage,而非整个DOM元素:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> #first{ height:20px;width:20px; border-radius:50%; border-width: 5px; background-color: green; } </style> </head> <body> <div id="first"></div> <input type="button" value="click here" onclick="doSomeThing()"> <form action="second-page.html"> <input type="submit" value="Click" onclick="passvalues()"/> </form> <script> function doSomeThing(){ const circle = document.getElementById("first"); circle.style.backgroundColor='red'; // 点击变色时同步存储颜色 localStorage.setItem("circleColor", circle.style.backgroundColor); } function passvalues(){ const circle = document.getElementById("first"); // 若未点击变色按钮,获取当前实际显示的颜色(默认绿色) const currentColor = circle.style.backgroundColor || getComputedStyle(circle).backgroundColor; localStorage.setItem("circleColor", currentColor); return true; } </script> </body> </html>
修改第二个页面代码
删除重复ID,读取localStorage中的颜色值并设置到圆圈上:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> #first{ height:20px;width:20px; border-radius:50%; border-width: 5px; background-color: green; } </style> </head> <body> <div id="first"></div> <script> const circle = document.getElementById("first"); const savedColor = localStorage.getItem("circleColor"); // 有保存的颜色则设置,否则使用默认绿色 if(savedColor){ circle.style.backgroundColor = savedColor; } </script> </body> </html>
额外说明
getComputedStyle用于获取元素最终的计算样式,因为初始状态下圆圈背景色由CSS类设置,element.style.backgroundColor会是空值,需要用这个方法拿到实际显示的颜色。- 既可以在点击变色按钮时存储颜色,也可以在提交表单时统一存储,两种方式都能实现状态同步。
内容的提问来源于stack exchange,提问作者jere6052
相关产品推荐
相关产品推荐

