伪类+js实现CSS3 media queries跨界准确判断实例页面

回到相关文章 »

代码:

CSS代码:
.demo img {
    width: 512px;
}
@media screen and (max-width: 1024px) {
    body:after {
        display: none;
        content: 'normalscreen';
    }
    .demo img {
        width: 256px;
    }
}                
JS代码:
var oDemo = document.getElementById("demo"), oImage = null, screenTypeCache;	
var funImage = function() {
    var screenType = window.getComputedStyle(document.body, ":after").getPropertyValue("content");
    if (screenTypeCache !== screenType) {
        var src = "//image.zhangxinxu.com/image/study/s/"+ (/normalscreen/.test(screenType)? "s256": "s512") +"/mm1.jpg";
        if (oImage === null) {
            oImage = document.createElement("img");
            oDemo.appendChild(oImage);
        }
        oImage.src = src;
        screenTypeCache = screenType;
    }
};
if (window.getComputedStyle) {
    window.addEventListener("resize", funImage);    
    funImage();
} else {
    oDemo.innerHTML = '<img src="//image.zhangxinxu.com/image/emtion/litter-sad.png" /><p>对不起,您的浏览器目前还不支持该功能!</p>';
}
                

效果: