h5中的classlist_HTML5 classList API

h5中的classlist

Having thrust myself into the world of JavaScript and JavaScript Libraries, I've often wondered: When are browser vendors going to see the helper methods/libraries created by the JavaScript toolkits and implement these functionalities natively within the browser? I realize that standards are important and browser vendors can't afford to half-ass these implementations but I do believe they could be...expedited.  The good news is that one of these functionalities has been add to the HTML5 API; classList.

使自己进入JavaScript和JavaScript库的世界,我常常想知道: 浏览器供应商何时会看到由JavaScript工具包创建的帮助方法/库,并在浏览器中本地实现这些功能? 我意识到标准很重要,浏览器供应商负担不起这些实施的费用,但我确实相信它们可以...加快开发速度。 好消息是,这些功能之一已添加到HTML5 API中。 classList 。

The classList object, added to all nodes within the DOM, provides developers methods by which to add, remove, and toggle CSS classes on a node.  classList also allows developers to check if a CSS class has been assigned to a given node.

添加到DOM内所有节点的classList对象为开发人员提供了在节点上添加,删除和切换CSS类的方法。 classList还允许开发人员检查CSS类是否已分配给给定节点。

Element.classList (Element.classList)

The classList object contains a number of helpful methods:

classList对象包含许多有用的方法:


{
	length: {number}, /* # of class on this element */
	add: function() { [native code] },
	contains: function() { [native code] },
	item: function() { [native code] }, /* by index */
	remove: function() { [native code] },
	toggle: function() { [native code] }
}


Element.classList, as you can see, is a small but useful collection of methods.

如您所见,Element.classList是一个很小但有用的方法集合。

添加一个CSS类 (Adding a CSS Class)

The add method allows you to add one more multiple space-separated classes:

使用add方法,您可以再添加一个多个以空格分隔的类:


myDiv.classList.add('myCssClass');


删除CSS类 (Removing a CSS Class)

The add method allows you to remove a single class:

add方法允许您删除单个类:


myDiv.classList.remove('myCssClass');

You could separate multiple classes by space but the result may not be incredibly reliable.

您可以按空间分隔多个类,但结果可能并不十分可靠。

切换CSS类 (Toggling a CSS Class)


myDiv.classList.toggle('myCssClass'); //now it's added
myDiv.classList.toggle('myCssClass'); //now it's removed

Note: If toggle is called and the element does not have the provided CSS class, the class is added.

注意:如果调用了toggle且元素没有提供CSS类,则会添加该类。

包含CSS类检查 (Contains CSS Class Check)


myDiv.classList.contains('myCssClass'); //returns true or false


The classList API is now supported by all modern browsers, so look for the JavaScript libraries to include classList checks instead of parsing an element's class attribute!

现在所有现代浏览器都支持classList API,因此请查找JavaScript库以包含classList检查,而不是解析元素的class属性!

翻译自: https://davidwalsh.name/classlist

h5中的classlist

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值