日期:2014-05-16 浏览次数:20497 次
发布一个js判断样式className和增加class删除class的通用代码,部分代码参考prototype.js
<HTML> <HEAD> <TITLE>testClassName</TITLE> </HEAD> <BODY> <p> </p> <div id="cc" 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($("cc"), "rr"); alert($("cc").className); BrowserCompatible.removeClassName($("cc"), "ee"); alert($("cc").className); </script> </BODY> </HTML>? |
?
原文链接:http://hi.baidu.com/jsdevelop/blog/item/0a67f517eee52f1e972b43ae.html/cmtid/572567a6fdcc9a9bd043586b