首页 > 解决方案 > 使用 JavaScript 选择 CSS 主题

问题描述

我正在运行一个仅限本地的站点,而不是在网络服务器上。

我有几个用户可选择的 CSS 样式。如果直接在页面上,则使用此代码非常有效。

<div class="themeselect">
<table><tr>
<td><a href="#" onclick="localStorage.setItem('style','screen');location.reload()"><i class="far fa-sun"></i></a></td>
<td><a href="#" onclick="localStorage.setItem('style','highcontrast');location.reload()"><i class="far fa-moon"></i></a></td>
</tr></table>
</div>

我想将该带有<script src="js/themeselect.js"></script>语句的 HTML 注入到带有外部 JS 文件的页面上。我已经尝试过了,但是单击链接没有任何作用。我认为这可能与单引号和/或双引号有关,但我似乎尝试了它们的每一种组合,但我无法弄清楚。

document.write("<div class='themeselect'>");
document.write("<table><tr>");
document.write("<td><a href='#' onclick='localStorage.setItem('style','screen');location.reload()'><i class='far fa-sun'></i></a></td>");
document.write("<td><a href='#' onclick='localStorage.setItem('style','highcontrast');location.reload()'><i class='far fa-moon'></i></a></td>");
document.write("</tr></table>");
document.write("</div>");

标签: javascripthtmlcss

解决方案


逃脱它!

检查我如何写第 3 行和第 4 行:

document.write("<div class='themeselect'>");
document.write("<table><tr>");
document.write("<td><a href='#' onclick=\"localStorage.setItem('style','screen');location.reload()\"><i class='far fa-sun'></i></a></td>");
document.write("<td><a href='#' onclick=\"localStorage.setItem('style','highcontrast');location.reload()\"><i class='far fa-moon'></i></a></td>");
document.write("</tr></table>");
document.write("</div>");

推荐阅读