如何使用 HTML 中的按钮来更改 <html> 元素的类名
How can I use buttons in my HTML to change the class name of the <html> element?
我有以下HTML,我的浏览器是IE9及以上版本,我们没有使用jQuery:
<html class="darkBlue">
我想做的是能够使用我的 HTML(下图)中的三个按钮在"深蓝色"、"黑色"和"红色"之间切换类,并让我的应用程序记住用户下次访问页面时的最后一个设置。
我在HTML中设置了以下内容:
<button>Blue</button>
<button>Black</button>
<button>Red</button>
如何轻松进行切换?我在想两件事:
- 有一个非常小的脚本,我可以在单击事件中调用。
- 在按钮的点击事件中对所有内容进行编码?
到目前为止,我学到的是,我需要像这样选择<html>
:
var elem = document.querySelector("html");
还建议我可以使用本地存储来存储最后选择的颜色。一些建议将不胜感激?
将 name 属性添加到按钮并使其成为您的 css 类名。
单行:
<button name="className1"
onclick="document.getElementsByTagName('html')[0].className=this.name;"
>Blue</button>
//other buttons
使用函数:
function changeColour(cName){
var elem = document.getElementsByTagName('html')[0];
elem.className = cName;
}
<button name="className1" onclick="changeColour(this.name)">Blue</button>
<button name="className2" onclick="changeColour(this.name)">Black</button>
<button name="className3" onclick="changeColour(this.name)">Red</button>
或者,您可以使用:
var elem = document.documentElement;
尝试
var elem = document.querySelector("html");
[].forEach.call( document.querySelectorAll('button'), function(el) {
el.addEventListener('click', changeColor);
});
function changeColor(event) {
//console.log( this.innerHTML);
if( this.innerHTML === 'Blue' ) {
elem.setAttribute( "class", "blueClass" );
}
else if( this.innerHTML === 'Red' ) {
elem.setAttribute( "class", "redClass" );
}
//Some things
}
希望对您有所帮助。
爪哇语
window.onload = function(){
var theme = localStorage.getItem("theme");
if(theme){
document.getElementsByTagName("html")[0].className = theme ;
}
}
function setClass(){
var html = document.getElementsByTagName("html")[0];
document.getElementsByTagName("html")[0].className = this.name;
localStorage.setItem("theme",this.name);
};
即使你最好使用querySelector而不是getElementsBytagName。
.html
<button name="dark" onclick="setClass()">Dark</button>
<button name="light" onclick="setClass()">Light</button>
相关文章:
- 如何设置html元素填充的动画
- 删除对HTML元素的拖动
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 如何使用JQuery在Javascript中转换字符串中的HTML元素
- 一个html元素的克隆次数太多
- 使用AngularJS Directive WHITOUT$scope创建一个动态html元素
- 为什么我在Internet Explorer上看不到html元素
- 重新排列HTML元素的顺序并更改内容
- 使用.on动态添加jquery/js不知道的html元素
- 如果类不是一个选项,如何在使用 jQuery 时控制(避免)嵌套 html 元素的样式
- 如何将html元素添加到tampermonkey中
- 访问html元素值javascript
- 如何在HTML元素上创建函数,而不是将元素作为参数传递
- 自定义HTML元素属性未显示-Web组件
- 让HTML元素充当停止滚动的锚点
- 将html元素插入到文本字符串中,以匹配另一个html字符串
- 替换HTML元素中的字符
- 如何将html元素添加为生成的内容
- 如何使用JavaScript在没有html dom的情况下隐藏html元素
- 使用JS加载HTML元素