• HTML5 classList API


    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.

    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.

    Element.classList

    The classList object contains a number of helpful methods:

    {
    	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.

    Adding a CSS Class

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

    myDiv.classList.add('myCssClass');

    Removing a CSS Class

    The add method allows you to remove a single class:

    myDiv.classList.remove('myCssClass');

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

    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.

    Contains CSS Class Check

    myDiv.classList.contains('myCssClass'); //returns true or false
    Some CSS properties may need to be vendor-prefixed.

    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!

  • 相关阅读:
    我已经迷失在事件环(eventloop)中了【Nodejs篇】
    canvas练手项目(二)——各种操作基础
    canvas练手项目(三)——Canvas中的Text文本
    canvas练手项目(一)——选取图片
    迭代器,生成器(generator)和Promise的“微妙”关系
    通过HTTP的HEADER完成各种骚操作
    这份Koa的简易Router手敲指南请收下
    KOA的简易模板引擎实现方式
    扒一扒PROMISE的原理,大家不要怕!
    参考KOA,5步手写一款粗糙的web框架
  • 原文地址:https://www.cnblogs.com/mqxnongmin/p/10681070.html
Copyright © 2020-2023  润新知