将document.body.className设置为变量 [英] Setting document.body.className as a variable

查看:186
本文介绍了将document.body.className设置为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,用于在用户点击链接时切换我的正文标记的类。

This is my code to switch the class of my body tag when a user clicks a link.

function switchBodyColor() {
    if (document.body.className == 'blue')
        document.body.className = 'red';
    else if (document.body.className == 'red')
        document.body.className = 'green';
    else if (document.body.className == 'green')
        document.body.className = 'blue';
}

我想将结果颜色设置为名为bodyColor的变量。因此,如果body类是蓝色并且用户单击并将其切换为red,我想将红色存储为变量(bodyColor)以供稍后用于其他用途。或者更好的是,将document.body.className设置为变量本身,然后使用该变量切换switchBodyColor()函数中的document.body.className。

I want to set the resulting color as a variable called bodyColor. So if the body class is "blue" and the user clicks and switches it to "red" I want to store red as a variable (bodyColor) for other uses later on. Or better yet, set document.body.className as a variable itself and then switch out document.body.className in the switchBodyColor() function with that variable.

我想以下内容:

    if (document.body.className == 'blue')
        document.body.className = 'red',
        var bodyColor = red;

var bodyColor = document.body.className

将body类设置为变量。

to set the body class as a variable.

当然,这两个选项都不起作用。 ^ _ ^;我怎样才能完成上述任何一个(或两个)?

Of course neither of those two options work. ^_^; How can I accomplish either (or both) of the above?

推荐答案

您需要将变量设为全局:

You need your variable to be global:

var bodyColor = 'red';  // Global var, initialized to your first color class

function switchBodyColor() {
    if (document.body.className == 'blue')
        document.body.className = 'red';
    else if (document.body.className == 'red')
        document.body.className = 'green';
    else if (document.body.className == 'green')
        document.body.className = 'blue';


    bodyColor = document.body.className;
    alert(bodyColor);
}

在你的另一个例子中,你还需要在颜色字符串周围加上引号:

In your other example, you also need to put quotes around your color string:

 bodyColor = "red";





另一种方法可能是为您的颜色类编号,这将允许您使用简单的算术来更改您的类,并允许您轻松更改您循环的类的数量。



Another way to do this might be to number your color classes, which will let you use simple arithmetic to change your classes and allows you to easily change the number of classes you are cycling through.

var colorNum = 0;
var totalColors = 3;

function switchBodyColor() {
    colorNum = (colorNum+1)%totalColors;
    document.body.className = 'color'+colorNum;
}

你的css将是:

.color0 { background-color: blue; }
.color1 { background-color: red; }
.color2 { background-color: green; }

或者你的颜色类定义是什么。

Or whatever your color class definitions are.

这篇关于将document.body.className设置为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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