昨天聽w3ctech分享時候,說道orientationchange在不一樣OS和版本中,存在兼容問題,不少時候觸發時候都沒有渲染結束,開發同窗通常都是基於setTimeout一段時間以後,在去執行具體的註冊事件css
相似這樣的系統兼容問題還有不少,其核心緣由在於html
1. 渲染未結束,js事件提早出發或者延後觸發web
2. 沒法根本之道什麼時候渲染完畢,只能用setTimeout估摸具體時間api
因此這裏本質上仍是js對於渲染模型的觀察者模式public的api不夠詳細形成,因此咱們就想到一個旁敲側擊的方式,app
1. 經過media query之類的Observe來作實時觀察ui
2. 再結合reflow/repaint會觸發resize事件的特質作到及時響應this
實現代碼以下:編碼
jsfile(testOrientation.js)spa
require([ 'common' ], function($) {
$('#J_block').bind('resize', function() {
alert($(this).css('background-color'))
})
window.addEventListener("orientationchange", function() {
var color = $('#J_block').css('background-color');
$('<div>' + color + '</div>').appendTo(document.body);
}, false);
})
htmlfilecode
<!doctype html>
<html>
<head>
<!--# include virtual="/t/common/index/header.html" -->
<style>
@media screen and (orientation:landscape){
#J_block{
background-color:green;
}
}
@media screen and (orientation:portrait){
#J_block{
background-color:red;
}
}
</style>
</head>
<body>
<div style="margin-top:10px;text-align:center" id="J_block">kqwjelqjwelkqwjelk</div>
<script src="<!--# include virtual="/t/common/loadRequireUrl.variable" -->?<!--# include virtual="/t/common/gb_version.variable" -->"></script>
<script>
require([ '<!--# include virtual="/t/common/loadConfigUrl.variable" -->?<!--# include virtual="/t/common/gb_version.variable" -->' ], function() {
require([ 'test/testOrientation' ]);
});
</script>
</body>
</html>
依照這個思路,還能夠觸類旁通,如
1. 基於Css實現的text-ellipsis屬性+resize事件,能夠算不一樣屏幕下是否超過字符上限
2. 基於Css實現dataURI實現base64 HTML code實現JS字符編碼轉換,見我以前的一篇文章http://www.cnblogs.com/xueduanyang/archive/2013/05/30/3108442.html
3. 基於Css的media query實現各類機型探測
4. 基於Css的rem屬性實現放大鏡同步
5. 基於Css的webkit-calc,實現寬度自適應
等等等等
歡迎和你們一塊兒討論