如何用JavaScript获取开关值写入在线txt文件并在网页加载时更新开关状态
实现方案说明
浏览器端运行的JavaScript受安全策略限制,无法直接写入远程服务器的txt文件,这和你之前用的Python服务端脚本逻辑有差异。根据你的需求分两种实现场景:
方案1:单设备本地状态持久化(无需后端)
如果只需要同一设备打开页面时记住之前的开关状态,用浏览器自带的localStorage就能实现,不需要额外服务,完整代码如下:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>明暗模式切换</title> <style> .switch { position: relative; display: inline-block; width: 60px; height: 34px; } .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; -webkit-transition: .4s; transition: .4s; } input:checked+.slider { background-color: #2196F3; } input:focus+.slider { box-shadow: 0 0 1px #2196F3; } input:checked+.slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); } /* 圆角滑块 */ .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; } </style> </head> <body> <h2>Dark and Day Mode</h2> <label class="switch"> <input type="checkbox" id="modeSwitch" checked /> <span class="slider round"></span> </label> <script> const switchEl = document.getElementById('modeSwitch') // 页面加载时读取本地存储的状态 const savedStatus = localStorage.getItem('switchStatus') if(savedStatus !== null) { switchEl.checked = savedStatus === 'true' } // 监听开关切换,保存状态到本地 switchEl.addEventListener('change', () => { localStorage.setItem('switchStatus', switchEl.checked) }) </script> </body> </html>
逻辑说明:
- 页面加载时优先读取本地存储的开关状态,没有的话用默认的选中状态
- 每次切换开关都会自动把最新状态存入本地存储,刷新、关闭重开页面都会保留状态
方案2:跨设备同步状态(搭配Python后端)
如果需要多设备打开页面都能同步开关状态,可以用你熟悉的Python写一个极简的后端服务,负责读写txt文件,前端调用接口同步状态:
第一步:后端Python代码(Flask实现)
from flask import Flask, request from flask_cors import CORS app = Flask(__name__) CORS(app) # 解决跨域问题,允许前端调用接口 # 存储状态的txt文件路径 STATUS_FILE = 'switch_status.txt' # 初始化文件,默认状态是开启 try: with open(STATUS_FILE, 'r') as f: pass except FileNotFoundError: with open(STATUS_FILE, 'w') as f: f.write('true') # 读状态接口 @app.route('/status', methods=['GET']) def get_status(): with open(STATUS_FILE, 'r') as f: return f.read().strip() # 写状态接口 @app.route('/status', methods=['POST']) def set_status(): status = request.get_data(as_text=True) with open(STATUS_FILE, 'w') as f: f.write(status) return 'ok' if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
运行后端前先装依赖:pip install flask flask-cors,运行后后端地址是http://localhost:5000
第二步:修改前端JS代码
把之前方案1的JS部分替换成下面的代码,就能和后端同步状态:
const switchEl = document.getElementById('modeSwitch') // 页面加载时从后端读取状态 fetch('http://localhost:5000/status') .then(res => res.text()) .then(status => { switchEl.checked = status === 'true' }) // 监听开关切换,把状态写入后端 switchEl.addEventListener('change', () => { fetch('http://localhost:5000/status', { method: 'POST', body: String(switchEl.checked) }) })
所有设备打开网页时都会从后端txt文件读取最新状态,切换开关也会实时更新txt里的内容,实现多设备同步。
内容的提问来源于stack exchange,提问作者SimpleGuy_
相关产品推荐
相关产品推荐

