關(guān)于媒體查詢
一般樣式的改變使用cs3的媒體查詢
行為和功能的改變使用JS的媒體查詢
1.css 媒體查詢
使用css3 @media screen
@media only screen and (device-width:360px) and (device-height:760px) and (-webkit-device-pixel-ratio:3){
//some css...
}
例如:
.example {
padding: 20px;
color: white;
}
/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {
.example {background: red;}
}
/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {
.example {background: green;}
}
/* Medium devices (landscape tablets, 768px and up) */
@media only screen and (min-width: 768px) {
.example {background: blue;}
}
/* Large devices (laptops/desktops, 992px and up) */
@media only screen and (min-width: 992px) {
.example {background: orange;}
}
/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {
.example {background: pink;}
}
2.js 媒體查詢
matchMedia()方法參數(shù)可寫任何一個(gè)CSS@media規(guī)則解总,返回的是新的MediaQueryList對(duì)象意推,該對(duì)象有兩個(gè)屬性:
media:查詢語(yǔ)句的內(nèi)容
matches:檢查查詢結(jié)果,返回boolean
還有兩個(gè)方法
addListener():添加一個(gè)新的監(jiān)聽(tīng)器函數(shù)予权,查詢結(jié)果改變時(shí)帽衙,調(diào)用指定回調(diào)
removeListener():刪除之前添加的監(jiān)聽(tīng)器啼辣,若不存在則不執(zhí)行任何操作
var medias = [
window.matchMedia('(max-width:418px)'), //注意添加括號(hào)协饲,和CSS一樣粥喜,也要注意順序凸主!
window.matchMedia('(max-width:768px)'),
window.matchMedia('(max-width:992px)'),
window.matchMedia('(max-width:1200px)')
]
function mediaMatches() {
if(medias[0].matches){
console.log('<=418'); //do something...
}else if(medias[1].matches){
console.log('>418 & <=768'); // do something...
}else if(medias[2].matches){
console.log('>768 & <=992'); // do something...
}else if(medias[3].matches){
console.log('> 992 & <=1200'); // do something...
}else {
console.log('>1200');
}
}
mediaMatches(); //頁(yè)面首次加載
for(var i = 0; i < sqls.length; i++){
medias[i].addListener(mediaMatches);
}
為每個(gè)MediaQueryList對(duì)象添加監(jiān)聽(tīng)器,每個(gè)對(duì)象查詢結(jié)果只有ture和false额湘,當(dāng)某個(gè)對(duì)象的查詢結(jié)果改變時(shí)都會(huì)調(diào)用指定回調(diào)函數(shù)mediaMatches秕铛,這樣就可以在每次頁(yè)面大小改變時(shí)執(zhí)行某些行為
關(guān)于viewport 參考https://www.cnblogs.com/2050/p/3877280.html