如何通过javascript将CSS类附加到元素? [英] how to append a css class to an element by javascript?

查看:123
本文介绍了如何通过javascript将CSS类附加到元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设HTML元素的 id 是已知的,因此可以使用以下形式引用元素:

Suppose a HTML element's id is known, so the element can be refereced using:

document.getElementById(element_id);

是否存在可用于向该元素追加CSS类的本机Javascript函数? p>

Does a native Javascript function exist that can be used to append a CSS class to that element?

推荐答案

var element = document.getElementById(element_id);
element.className += " " + newClassName;

Voilà。这将几乎工作在每个浏览器。领先的空间很重要,因为 className 属性将css类视为单个字符串,应该匹配 class 属性(其中多个类必须用空格分隔)。

Voilà. This will work on pretty much every browser ever. The leading space is important, because the className property treats the css classes like a single string, which ought to match the class attribute on HTML elements (where multiple classes must be separated by spaces).

顺便说一句,你会更好地使用像Javascript这样的库,例如原型 jQuery ,其中有方法可以执行此操作,以及可以首先

Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.

在原型中,例如:

// Prototype automatically checks that the element doesn't already have the class
$(element_id).addClassName(newClassName);

看看有多少钱?

这篇关于如何通过javascript将CSS类附加到元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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