代码改变世界

利用 Javascript 让 DIV 自适应屏幕的分辨率,从而决定是否显示滚动条

  音乐让我说  阅读(1110)  评论(0编辑  收藏  举报

直接贴代码了:

复制代码
<!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>
复制代码

 

运行效果:

 

谢谢浏览!

点击右上角即可分享
微信分享提示