使用 javascript 在运行时更改整个网站的样式表 [英] Changing style sheets for entire website at runtime using javascript

查看:30
本文介绍了使用 javascript 在运行时更改整个网站的样式表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用 xhtml 和 css 来创建一个网站.我没有 Javascript 经验,但使用 this turorial 来改变风格使用按钮在运行时工作表.

So i'm using xhtml and css to create a website. I have no Javascript experience but used this turorial in order to change style sheets at runtime using a button.

所以我脑子里的代码是

<link id="pagestyle"
        rel = "stylesheet"
        href = "projectstylesheet.css"
        type = "text/css"
        />
        <script type="text/javascript">
            function swapStyleSheet(sheet) {
                document.getElementById('pagestyle').setAttribute('href', 
sheet);
            }
        </script>

我的按钮代码是

<button onclick="swapStyleSheet('projectstylesheetalternate.css')">
                Alternate Stylesheet
</button>

如何让样式表更改保持不变,以便在切换页面时它不会恢复到原始样式表.

How would I let the stylesheet change stick, so it doesn't revert to the original stylesheet when I switch pages.

推荐答案

您有多个选项可以使样式表永久更改:

You have multiple options to make the stylesheet change permanent:

  1. 您以不需要重新加载真实页面的方式开发您的网站,例如通过异步加载新内容.然后保存用户样式表决定",直到他点击重新加载按钮

  1. You develop your Website in a way that doesn't require real page reloads e.g. by asynchronously loading new content. The users "stylesheet decision" is then saved until he hits the reload button

单击按钮时,您还会向服务器发送请求并将样式表路径保存在用户会话数据中.然后,只要会话持续,用户的决定就会被保存,通常直到用户退出浏览器.

On button click you also send a request to the server and save the stylesheet path in the users session data. The users decision is then saved for as long as the session lasts, which is usually until the user quits their browser.

您将样式表路径存储在 cookie、localStorage 中或将其缓存在客户端的其他位置.更改将是永久性的,直到用户清除其 cookie、缓存等.

You store the stylesheet path in a cookie, the localStorage or cache it somewhere else in the client. The change is then permanent until the user clears its cookies, cache etc.

您让用户在您的页面上注册,并且 - 类似于方法 1 - 在单击按钮时向服务器发出请求.但是这一次您没有将值存储在会话中,而是存储在链接/用户配置文件的一部分的数据库表中.更改实际上是永久性的,只要您不提供将样式表更改回来的方法,用户就无法这样做(除了注册新帐户)

You make the user sign up on your page and - similar to approach 1 - make a request to the server on button click. But this time you don't store the value in the session but in a database table which is linked/part of the users profile. The change is then really permanent and as long as you don't provide a way to change the stylesheet back there is no way for the user to do so (apart from registering a new account)

我认为解决方案 3 最适合您的需求.因此,您可能希望使用像 js-cookie 这样的库来实现这一点.

I think Solution No. 3 suits your needs best. So you might want to use a library like js-cookie to to achieve this.

这篇关于使用 javascript 在运行时更改整个网站的样式表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆