zoukankan      html  css  js  c++  java
  • 根据不同分辨率载入相应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; }
  • 相关阅读:
    css 图片的无缝滚动
    有时间研究下这个
    js的类数组对象
    js的this什么时候会出现报错
    js前端分页
    js队列
    js前端处理url中的参数为对象
    随机看的一点代码
    js的callee和caller方法
    js的Object和Function
  • 原文地址:https://www.cnblogs.com/baie/p/3160456.html
Copyright © 2011-2022 走看看