html媒体查询怎么把颜色换成图片,为网页中图片src添加媒体查询功能。
为图片src 增加媒体查询。
Css 中的媒体查询默认是没有为图片指定src,的 但是如果页面中需要根据浏览器宽度指定图片src, 比如当电脑的时候,加载大图,手机的时候加载小图。
今天发现一个很棒的方法,相当于通过js可以扩展浏览器的媒体查询,
Picturefillbody { font-family: sans-serif }
img { max-width: 100% }
Picturefill: A <picture> element polyfill
For more info: see project home.
在页面中这样写,然后js这样处理
/*! Picturefill - Responsive Images that work today. (and mimic the proposed Picture element with span elements). Author: Scott Jehl, Filament Group, 2012 | License: MIT/GPLv2 */
(function( w ){
// Enable strict mode
"use strict";
w.picturefill = function() {
var ps = w.document.getElementsByTagName( "span" );
// Loop the pictures
for( var i = 0, il = ps.length; i
if( ps[ i ].getAttribute( "data-picture" ) !== null ){
var sources = ps[ i ].getElementsByTagName( "span" ),
matches = [];
// See if which sources match
for( var j = 0, jl = sources.length; j
var media = sources[ j ].getAttribute( "data-media" );
// if there's no media specified, OR w.matchMedia is supported
if( !media || ( w.matchMedia && w.matchMedia( media ).matches ) ){
matches.push( sources[ j ] );
}
}
// Find any existing img element in the picture element
var picImg = ps[ i ].getElementsByTagName( "img" )[ 0 ];
if( matches.length ){
var matchedEl = matches.pop();
if( !picImg || picImg.parentNode.nodeName === "NOSCRIPT" ){
picImg = w.document.createElement( "img" );
picImg.alt = ps[ i ].getAttribute( "data-alt" );
}
picImg.src = matchedEl.getAttribute( "data-src" );
matchedEl.appendChild( picImg );
}
else if( picImg ){
picImg.parentNode.removeChild( picImg );
}
}
}
};
// Run on resize and domready (w.load as a fallback)
if( w.addEventListener ){
w.addEventListener( "resize", w.picturefill, false );
w.addEventListener( "DOMContentLoaded", function(){
w.picturefill();
// Run once only
w.removeEventListener( "load", w.picturefill, false );
}, false );
w.addEventListener( "load", w.picturefill, false );
}
else if( w.attachEvent ){
w.attachEvent( "onload", w.picturefill );
}
}( this ));
就行了。
demo url: demo
总结
以上是生活随笔为你收集整理的html媒体查询怎么把颜色换成图片,为网页中图片src添加媒体查询功能。的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 玩游戏4g计算机的内存不足,window
- 下一篇: 计算机网络中的时延有哪几部分,计算机网络