Web程序员必备的7个JavaScript函数(2)

有时候我们会使用一个CSS选择器(比如 document.querySelectorAll)来获取一个 NodeList ,然后给它们每个依次修改样式。其实这并不是一种高效的做法,高效的做法是用JavaScript新建一段CSS样式规则:

// Build a better Sheet object Sheet = (function() { // Build style var style = document.createElement('style'); style.setAttribute('media', 'screen'); style.appendChild(document.createTextNode('')); document.head.appendChild(style); // Build and return a single function return function(rule){ style.sheet.insertRule( rule, style.sheet.cssRules.length ); } ; })(); // Then call as a function Sheet(".stats { position: relative ; top: 0px }") ;

这些做法的效率非常高,在一些场景中,比如使用ajax新加载一段html时,使用上面这个方法,你不需要操作新加载的html内容。

判断网页元素是否具有某种属性和样式 matchesSelector

function matchesSelector(el, selector) { var p = Element.prototype; var f = p.matches || p.webkitMatchesSelector || p.mozMatchesSelector || p.msMatchesSelector || function(s) { return [].indexOf.call(document.querySelectorAll(s), this) !== -1; }; return f.call(el, selector); } // Usage matchesSelector(document.getElementById('myDiv'), 'div.someSelector[some-attribute=true]')

就是这7个JavaScript函数,每个Web程序员都应该知道怎么用它们。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzsxfp.html