利用 Javascript 讓 DIV 自適應屏幕的分辨率,從而決定是否顯示滾動條


直接貼代碼了:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="resources/scripts/jquery-1.10.1.min.js"></script>
</head>
<body>
    <div class="core-title">
        <h2>這里是標題</h2>
    </div>
    <div id="coreComparisonReportDiv" style="overflow-y:scroll; ">
        <div class="tableShow">
            <table style="width:5000px;">
                <thead>
                    <tr>
                        <th>Remark</th>
                        <th>Data Set</th>
                        <!-- 假設這里還有很多列 -->
                    </tr>
                </thead>
                <tbody>
                    <tr style="">
                        <td style="width:120px; ">No Change</td>
                        <td style="width:250px; ">2019-03-15</td>
                        <!-- 假設這里還有很多列 -->
                    </tr>
                    <!-- 假設這里還有很多行 -->
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>

 

下面是 Javascript 腳本:

    <script type="text/javascript">
        $(document).ready(function () {
            calcCoreComparisonReportDivHeight();
        });
        function getTableSuggestHeight(id, errorHeightValue) {
            var jTable = $('#' + id);
            if (jTable.length == 0) {
                return;
            }
            var windowHeight = $(window).height();
            var jTableOffsetTop = jTable.offset().top;
            var iframeOffsetTop = 0;
            if (window.parent != null) {
                var appDivObj = window.parent.document.getElementById("app");
                if (appDivObj) {
                    var appDivObjOffsetTop = appDivObj.offsetTop;
                    iframeOffsetTop = appDivObjOffsetTop;
                }
            }
            var tempErrorHeightValue = 10;
            if (errorHeightValue) {
                tempErrorHeightValue = errorHeightValue;
            }
            var suggestHeight = windowHeight - jTableOffsetTop - iframeOffsetTop - tempErrorHeightValue; // 10 為誤差
            if (suggestHeight < 200) {
                suggestHeight = 200; // 為了兼容 1024*768 的顯示屏,最小高度 200
            }
            return suggestHeight;
        }
        function calcCoreComparisonReportDivHeight() {
            var coreComparisonReportDivId = "coreComparisonReportDiv";
            var coreComparisonReportDivHeight = getTableSuggestHeight(coreComparisonReportDivId);
            $("#" + coreComparisonReportDivId).height(coreComparisonReportDivHeight);
        }
        $(window).resize(function () {
            calcCoreComparisonReportDivHeight();
        });
    </script>

 

運行效果:

 

謝謝瀏覽!


免責聲明!

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



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