我有一个网站,我想为其添加不同的样式。用户可以选择任何他想要的样式,我将它存储在localStorage中并显示出来。我有这段代码:
<link href="default.css" type="text/css" rel="stylesheet" onload="this.href = window.localStorage['webpage_style'];"/>
这工作正常,但按钮有问题。 default.css
是白色风格——就像这里的堆栈溢出一样。但是新的是深色风格,有深灰色背景等等。我的按钮问题是:在使用新的深色样式加载的每个页面上,按钮都是白色的,然后迅速变为深色,但白色时刻清晰可见,看起来很糟糕。我可以做些什么来阻止对页面加载的影响?
这是两个 CSS:
button {
width: 88%;
padding: 1.5em;
background-color: white;
border: 1px solid black;
margin: 1.8%;
margin-bottom: 0.2%;
cursor: pointer;
transition: background-color 0.3s ease-in-out;
}
button:hover {
background-color: #e8e8e8;
}
button:focus {
outline: none;
}
<button>Sample - Default CSS</button>
button {
width: 88%;
padding: 1.5em;
background-color: white;
border: 1px solid #c8c8c8;
/* Change here */
margin: 1.8%;
margin-bottom: 0.2%;
cursor: pointer;
transition: background-color 0.3s ease-in-out;
background-color: #272323;
/* Change here */
color: #c8c8c8;
/* Change here */
}
button:hover {
background-color: #3b3636;
/* Change here */
}
button:focus {
outline: none;
}
<button>Sample - Dark CSS</button>
我该怎么做才能不显示这种效果?按钮在 0.3 秒内从白色变为黑色。有什么办法吗?或者我应该只删除 CSS 中的过渡线(这会停止效果,但还有其他方法吗)?
最佳答案
你告诉浏览器等待 load-event ,这个(来自前面提到的 MDN 文档):
...fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.
因此,如果您不需要等待 DOM 就绪,请不要使用 onload
。
<link href="default.css" type="text/css" rel="stylesheet" id="dynamic_stylesheet" />
<script>
if (window.localStorage['webpage_style']) {
var styleLink = document.getElementById("dynamic_stylesheet");
styleLink.href = window.localStorage['webpage_style'];
}
</script>
或者,如果仍然引入了 flash,您可以在 JS 中有条件地编写样式链接。
<script>
if (window.localStorage['webpage_style']) {
document.write("<link href=\""+window.localStorage['webpage_style']+"\" type=\"text/css\" rel=\"stylesheet\" />");
} else {
document.write("<link href=\"default.css\" type=\"text/css\" rel=\"stylesheet\" />");
}
</script>
<noscript>
<link href="default.css" type="text/css" rel="stylesheet" />
</noscript>
关于Javascript - 更改页面样式而不显示上一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46002188/