使用javascript添加类,而不是替换 [英] Adding a class with javascript, not replace

查看:136
本文介绍了使用javascript添加类,而不是替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够向元素添加一个类,而不是替换已经存在的类。

I would like the ability to add a class to an element and not replace what classes are already there.

这里是我的javascript到目前为止:

Here is my javascript so far:

function black(body) {
var item = document.getElementById(body);
    if (item) {
        item.className=(item.className=='normal')?'black':'normal';
    }
}

那个javascript替换现有的类c $ c> black 。如果类已经是 black ,那么它将更改为正常

That piece of javascript replaces the existing classes with black. If the class already is black then it is changed to normal.

我想以某种方式结合上面的脚本和下面的脚本,添加一个类,而不是替换所有现有的类。

I would like to somehow combine the script above with the script below script, which adds a class, instead of replacing all existing classes.

var item = document.getElementById("body");
item.className = item.className + " additionalclass";


推荐答案

这里有几个简单的javascript函数,类名在纯javascript中。在这些函数中需要一些额外的工作来匹配整个类名,并避免在类名之前/之后的任何额外的空格:

Here are several plain javascript functions you can use for manipulating class names in plain javascript. It takes a little extra work in these functions to match whole class names only and avoid any extra spaces before/after classnames:

function removeClass(elem, cls) {
    var str = " " + elem.className + " ";
    elem.className = str.replace(" " + cls + " ", " ").replace(/^\s+|\s+$/g, "");
}

function addClass(elem, cls) {
    elem.className += (" " + cls);
}

function hasClass(elem, cls) {
    var str = " " + elem.className + " ";
    var testCls = " " + cls + " ";
    return(str.indexOf(testCls) != -1) ;
}

function toggleClass(elem, cls) {
    if (hasClass(elem, cls)) {
        removeClass(elem, cls);
    } else {
        addClass(elem, cls);
    }
}

function toggleBetweenClasses(elem, cls1, cls2) {
    if (hasClass(elem, cls1)) {
        removeClass(elem, cls1);
        addClass(elem, cls2);
    } else if (hasClass(elem, cls2)) {
        removeClass(elem, cls2);
        addClass(elem, cls1);
    }
}

如果您想在 black normal 类,而不影响指定对象上的任何其他类,可以这样做:

If you wanted to toggle between the black and normal classes without affecting any other classes on the specified object, you could do this:

function black(id) {
    var obj = document.getElementById(id);
    if (obj) {
        toggleBetweenClasses(obj, "black", "normal");
    }
}

这里的工作示例: http://jsfiddle.net/jfriend00/eR85c/

如果您想要添加黑色类,除非normal已经存在,可以这样做:

If you wanted to add the "black" class unless "normal" was already present, you could do this:

function black(id) {
    var obj = document.getElementById(id);
    if (obj && !hasClass(obj, "normal")) {
        addClass(obj, "black");
    }
}

这篇关于使用javascript添加类,而不是替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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