在做自適應布局的時候,我們常常需要根據窗口不同的分辨率給出不同布局和樣式,今天說的onresize便能幫我們實現這一效果。
onresize事件在窗口或者框架的大小發生改變的時候會被調用,下面我們用一個例子來演示。
在這個例子中,我們想要實現的效果是:當屏幕寬度小於500時,頁面的背景色為灰色;當屏幕寬度大於等於500時,頁面背景為粉色;當屏幕寬度大於等於800時,頁面背景為紅色。所以,我們首先需要獲得屏幕的寬度,需要用到前面封裝的client方法。
<script> function client() { if(window.innerWidth){ return { width: window.innerWidth, height: window.innerHeight } }else if(document.compatMode === "CSS1Compat"){ return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight } } return { width: document.body.clientWidth, height: document.body.clientHeight } }</script>
要根據不同屏幕大小實現不同的效果,需要調用onresize事件。
<script> window.onload = function () { window.onresize = function(){ if(client().width >= 800){ document.body.style.backgroundColor = 'red'; }else if(client().width >= 500){ document.body.style.backgroundColor = 'pink'; }else { document.body.style.backgroundColor = 'gray'; } }; } </script>
現在基本功能已經實現,但是,前面一直提到onresize是在屏幕變化的時候才會被觸發調用,那么在初始化的時候,沒有發生屏幕變化,那么上面的顏色改變就不會被觸發,因此,我們需要將上面的代碼進行稍微的調整優化。
<script> window.onload = function () { var bgColor; // 初始化的時候觸發 changeColor(); // 窗口大小改變是觸發 window.onresize = changeColor; function changeColor() { if(client().width >= 800){ bgColor = 'red'; }else if(client().width >= 500){ bgColor = 'pink'; }else { bgColor = 'gray'; } document.body.style.backgroundColor = bgColor; } } </script>
至此,我們就利用onresize實現了想要的效果了。
完整詳細的代碼下載:點這里