1

我正在使用以下内容来更改与标签关联的类:

<html lang="en" class="darkBlue">

    <button name="darkBlue"
       onclick="document.getElementsByTagName('html')[0].className=this.name">Blue</button>
    <button name="black"
       onclick="document.getElementsByTagName('html')[0].className=this.name">Blue</button>

如何使用 localstorage 存储已单击的内容并使其成为默认设置,以便当用户访问该页面时。所以没有闪烁那么我应该<header>在页面标签内有一些javascript吗?

4

2 回答 2

2

这应该有效:

HTML

<button name="darkBlue" onclick="getButtonColor(this.name)" >Blue</button>
<button name="black" onclick="getButtonColor(this.name)" >Black</button>

Javascript

 if(localStorage.buttonColor) {
    document.getElementsByTagName('html')[0].className = localStorage.buttonColor
}

function getButtonColor(buttonName) {
    localStorage.buttonColor= buttonName;
    document.getElementsByTagName('html')[0].className = buttonName
}
于 2013-10-06T10:04:55.283 回答
0

好吧,这是简单的方法

HTML

<button name="darkBlue" onclick="handleClick(this.name);">Blue</button>
<button name="black" onclick="handleClick(this.name);">Blue</button>

JavaScript

if (localStorage.btnClass) {
    //alert(localStorage.getItem('btnClass'));

    document.getElementsByTagName('html')[0].className = localStorage
            .getItem('btnClass');

}
function handleClick(btnName) {
    localStorage.setItem('btnClass', btnName);
};

感谢 anne 指出 ID 应该是唯一的

于 2013-10-06T09:49:08.547 回答