根据不同分辨率载入相应CSS样式表
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>根据不同分辨率载入相应CSS样式表</title> <link href="default.css" rel="stylesheet" type="text/css" /> <script> var loadCss = (function () { var arrCss = [{minW: 768, maxW: 1024, src: 'style.css'}, {minW: 0, maxW: 768, src:'css.css'}]; loadCss(arrCss); bindEvent(window, 'resize', function () { loadCss(arrCss); }); function loadCss(arr) { var w = document.documentElement.clientWidth; for (var i = 0, len = arr.length; i < len; i++) { addCss(arr[i]); } function addCss(json) { var arr = document.getElementsByTagName('link'); var oCss = null; var bFlag = false; var bAdd = false; for(var i = 0; i < arr.length; i++) { if (arr[i].getAttribute('href') == json.src) { oCss = arr[i]; break; } } if (w >= json.minW && w <= json.maxW) { var css = document.createElement('link'); css.href = json.src; css.rel = 'stylesheet'; css.type = 'text/css'; insertAfter(css, arr[arr.length - 1]); } if (oCss) oCss.parentNode.removeChild(oCss); } } })(); function bindEvent(obj, events, fn) { obj.addEventListener ? obj.addEventListener(events, fn, false) : obj.attachEvent('on' + events, function () { fn.call(obj); }); } function insertAfter(newElement, targetElement) { var parent = targetElement.parentNode; if (last(parent) == targetElement) parent.insertBefore(newElement); else parent.insertBefore(newElement, next(targetElement)); } function next(obj) { return obj.nextElementSibling || obj.nextSibling; } function last(obj) { return obj.lastElementChild || obj.lastChild; } </script> </head> <body> </body> </html>
default.css
body { background:black; }
style.css
body { background:red; }
css.css
body { background:green; }