html媒体查询怎么把颜色换成图片,为网页中图片src添加媒体查询功能。
為圖片src 增加媒體查詢。
Css 中的媒體查詢默認(rèn)是沒有為圖片指定src,的 但是如果頁面中需要根據(jù)瀏覽器寬度指定圖片src, 比如當(dāng)電腦的時(shí)候,加載大圖,手機(jī)的時(shí)候加載小圖。
今天發(fā)現(xiàn)一個(gè)很棒的方法,相當(dāng)于通過js可以擴(kuò)展瀏覽器的媒體查詢,
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
總結(jié)
以上是生活随笔為你收集整理的html媒体查询怎么把颜色换成图片,为网页中图片src添加媒体查询功能。的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 玩游戏4g计算机的内存不足,window
- 下一篇: 计算机网络中的时延有哪几部分,计算机网络