一个用JS来给 HTML元素增加或删除className的例子
一个用JS来给 HTML元素增加或删除className的例子
<HTML> <HEAD> <TITLE>testClassName</TITLE> </HEAD> <BODY> <p> </p> <div id="testDiv" class="cc eee ee"></div> <script type="text/javascript"> function BrowserCompatible () {} BrowserCompatible.hasClassName = function(element, className) { if (!element) return; var elementClassName = element.className; if (elementClassName.length == 0) return false; //用正则表达式判断多个class之间是否存在真正的class(前后空格的处理) if (elementClassName == className || elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))) return true; return false; } BrowserCompatible.addClassName = function(element, className) { if (!element) return; var elementClassName = element.className; if (elementClassName.length == 0){ element.className = elementClassName; return; } if (elementClassName == className || elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))) return; element.className = elementClassName + " " + className; } BrowserCompatible.removeClassName = function(element, className) { if (!element) return; var elementClassName = element.className; if (elementClassName.length == 0) return; if(elementClassName == className) { element.className = ""; return; } if (elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))) element.className = elementClassName.replace((new RegExp("(^|\\s)" + className + "(\\s|$)"))," "); } function $(id){ return document.getElementById(id); } //alert(BrowserCompatible.hasClassName($("cc"), "cc")); BrowserCompatible.addClassName($("testDiv"), "rr"); alert($("testDiv").className); BrowserCompatible.removeClassName($("testDiv"), "ee"); alert($("testDiv").className); </script> </BODY> </HTML>
相关推荐
IdeaElements 2020-08-19
阿斌Elements 2020-06-11
wikiwater 2020-10-27
Sophiego 2020-08-16
Kakoola 2020-08-01
Kakoola 2020-07-29
ELEMENTS爱乐冬雨 2020-07-18
ELEMENTS爱乐小超 2020-07-04
ELEMENTS爱乐小超 2020-07-04
Kakoola 2020-06-28
Feastaw 2020-06-18
Wmeng0 2020-06-14
ELEMENTS爱乐冬雨 2020-06-14
云之高水之远 2020-06-14
哈喽elements 2020-06-14