1. 程式人生 > >設置窗口的自適應大小

設置窗口的自適應大小

計時 執行函數 body ali border 高度 解決 用戶 overflow

在網頁設計時經常遇到需要背景圖或者輪播圖等情況,為了滿足眾多用戶的不同需求,我們又不能一次性的定死頁面的寬和高,所以需要使用一些手段是窗口達到自適應的目的,在今天的開發中,遇到這個問題並找到了解決的方法

    <script type="text/javascript">
        // 窗口的自適應大小
        window.onload = windowHeight; //頁面載入完畢執行函數
        function windowHeight() {
            var h = document.documentElement.clientHeight; //
獲取當前窗口可視操作區域高度 var bodyHeight = document.getElementById("my-index"); //尋找ID為content的對象 bodyHeight.style.height = (h - 25) + "px"; //你想要自適應高度的對象 } setInterval(windowHeight, 500)//每半秒執行一次windowHeight函數 </script>

通過上面的代碼可以獲取當前窗口的高度,並將得到的數值賦值給自適應的對象,這樣子就可以達到窗體自適應的效果了

但需要註意的是 窗口自適應意味著CSS不可以給窗體設置固定的寬和高,在這裏一般使用百分比,所以需要一定的想象力,否則頁面內的元素會顯得亂而無章

 body {
            padding-top: 10px;
            padding-bottom: 20px;
            height: 100%;
        }

        .modal-body p span {
            font-family: 微軟雅黑;
            font-size: 14px;
            color: black;
        }

        #my-index 
{ min-height:200px; min-width: 300px; background-size: 100%, 100%; background-image: url("image/temp01.jpg"); } .logo{ position: absolute; left: 37.5%; top: 37.5%; border-radius: 10px; width: 25%; height: 25%; background-color: white; text-align: center; } .logo .logo-icon{ height: 50%; width: 80%; text-align: center; overflow: hidden; } .logo .logo-icon img{ width: 100%; text-align: center; margin: 10% 0 10% 20%; } .logo .logo-link{ font-size: 20px; font-weight: bold; margin-top: 15%; } .com-intro{ position: absolute; left: 15%; top: 20%; border-radius: 20%; width: 25%; height: 25%; background-color: cyan; text-align: center; } .com-intro p{ font-size: 50px; margin-top: 20%; } .com-intro-menu{ display: none; } .com-products{ position: absolute; right: 15%; top: 20%; border-radius: 20%; width: 25%; height: 25%; background-color: cyan; text-align: center; } .com-products p{ font-size: 50px; margin-top: 20%; } .com-study{ position: absolute; left: 15%; bottom: 20%; border-radius: 20%; width: 25%; height: 25%; background-color: cyan; text-align: center; } .com-study p{ font-size: 50px; margin-top: 20%; } .com-join{ position: absolute; right: 15%; bottom: 20%; border-radius: 20%; width: 25%; height: 25%; background-color: cyan; text-align: center; } .com-join p{ font-size: 50px; margin-top: 20%; }

其次,文本居中問題,水平居中可以使用text-align:center,但不支持垂直居中,所以需要根據需要進行margin或者padding屬性調整,自適應的使用百分比,固定的可以直接使用像素

設置窗口的自適應大小