如何自動在html頁面加載時動態改變div等元素的高度和寬度


這里需要用到jquery + css。原理是在頁面加載時用javascript去動態改變一個class的高度和寬度。這樣結合javascript能動態獲取瀏覽器/頁面的高度和寬度,從而使得div能動態的跟隨瀏覽頁面的大小變化而變化並且不影響高寬比。下面的代碼創建一個手機頁面,每一行三個圖片分占33%,每個圖片div的高和寬會隨着瀏覽器的大小變化而自適應。

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta id="viewport" name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
    <title>test photoview</title>
</head>

<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">

    function pageload()
    {
        var size = {
            width: window.innerWidth || document.body.clientWidth,
            height: window.innerHeight || document.body.clientHeight
        }

        var cw = (size.width - 60) / 3;
        $('.autowidth').css({ 'width': cw + 'px' });
        $('.autowidth').css({ 'height': cw + 'px' });
    }

    window.onload = pageload;

</script>

<style>
    .bodyclass{
        background-color:#dedbdb;
    }
    .studentblock {
        font-family:微軟雅黑;
    }
    .studentblock:hover {
        border:2px solid blue;
        border-color:blue;
        cursor:pointer;
    }
    .autowidth {
        height:100px;
        background-size:cover;
        margin-left:8px;
        margin-top:0px;
    }
    .autowidth:hover {
        border: 2px solid blue;
        cursor: pointer;
    }
    .tdsection {
        width:33%;
        padding-bottom:5px;
    }
</style>

<body class="bodyclass">
<div style="width:100%;height:1000px;overflow-x:hidden;overflow-y:hidden;">
    <table style="width:100%">
        <tr>
            <td class="tdsection">
                <div class="autowidth" style="background-image:url('image/people1.jpg');"></div>
                <div style="background-color:#ffffff;margin-left:8px;font-family:微軟雅黑;text-align:center;">春游</div>
            </td>
                                                        
            <td class="tdsection">
                <div class="autowidth" style="background-image:url('image/people1.jpg');""></div>
                <div style="background-color:#ffffff;margin-left:8px;align-content:center;font-family:微軟雅黑;text-align:center;">春游</div>
            </td>
                                                        
            <td class="tdsection">
                <div class="autowidth" style="background-image:url('image/people1.jpg');"></div>
                <div style="background-color:#ffffff;margin-left:8px;align-content:center;font-family:微軟雅黑;text-align:center;">春游</div>
            </td>                                          
        </tr>
    </table>
</div>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM