jQuery動態定位

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   sp   java   

關於頁面配置這個問題,一直很糾結,之前一直不知道如何footer定位,後來想了想用jQuery就可以實現這些功能於是自己花了點時間弄了一個頁面,可以動態設定根據#header的高度動態設定#main和#footer的位置。

css

body,html{    margin: 0;    padding: 0;    border: 0;    height: 100%;}#container{    min-width: 100%;    min-height: 100%;    position: relative;    margin: 0;}#header{    width: 100%;    height: 150px;    background: #f0f;    position: absolute;    margin: 0;}#main{    width: 100%;    height: 700px;    background: #f00;    position: absolute;    margin-top: 150px;}#footer{    width: 100%;    height: 50px;    background: #0f0;    position: absolute;}

 

思路:一、設定一個#container包裹#header、#main、#footer

二、首先要給 html 和 body 元素設定高度(height屬性)為100%,這樣先保證根項目的高度撐滿整個瀏覽器視窗,然後下面才能使 #container 的高度撐滿整個瀏覽器視窗。至於為什麼用同時設定 html 和 body 元素,是因為 Firefox 和 IE 認為的根項目不一樣,因此這裡都給他們設定上。

三、設定#container為相對定位,

將 #container 設定為相對定位(第9行),目的是使他成為它裡面的 #footer 的定位基準,也就是所謂的“最近的定位過的祖先元素”。然後把 #foooter 設定為絕對位置並使之貼在 #container 的最下端。設定min-height為100%。min-height 屬性的作用就是使 #container 的高度“至少”為瀏覽器視窗的高度,而當如果它裡面的內容增加了,他的高度會也跟隨著增加,這才是我們需要的效果。

四、設定#header的值,然後根據#header的height值設定#main的margin-top的值。這樣可以設定兩個div的距離為0,然後用jQuery動態擷取#header的值和#main的值然後將#footer的margin-top值設定為#main和#header的高度的和

這樣就可以將footer定位在最下方了。

html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>頭部</title>    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1">    <link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">    <link rel="stylesheet" type="text/css" href="resource/css/bootstrap.css">    <link rel="stylesheet" type="text/css" href="resource/css/common.css">    <script src="resource/js/jquery-2.1.1.js"></script>    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>    <script src="resource/js/bootstrap.js"></script>    <script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script></head><body>    <div id="container">        <div id="header">header</div>        <div id="main">content</div>        <div id="footer">footer</div>    </div>    <script type="text/javascript">    $(function(){        var a=$("#main").height()+$("#header").height();        var marginTop=a+‘px‘;        $("#footer").css("margin-top",marginTop);    });    </script></body></html>

 

jQuery動態定位

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.