javascript - 如何让网页不刷新的情况下动态改变div布局?
天蓬老师
天蓬老师 2017-04-11 11:15:59
[JavaScript讨论组]

我想让这个页面随着我用鼠标调整浏览器大小而随时适应到该有的样子,该如何去做呢?

下面是代码,这个代码布局不会随着浏览器大小改变即时改变,必须刷新才行。如何改进呢?

<html>
<style>
*{margin:0;padding:0;border:0;}
#x1{width:100%;background:grey;}
#x2{width:100%;height:30px;background:yellow;}
</style>

<body>
<p>
<p id="x1"></p>
<p id="x2"></p>
</p>
</body>
<script>
var h1 = document.body.scrollHeight;
var get_x1 = document.getElementById('x1');
get_x1.style.height = h1-30;
</script>
</html>

谢谢

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(4)
PHPz

如果不考虑兼容性的话,可以使用calc函数,它会自动帮你计算的

<html>
<style>
*{margin:0;padding:0;border:0;}
html,body{height:100%}
#container{height: 100%}
#x1{width:100%;background:#CCC;
    height:-moz-calc(100% - 30px);
    height:-webkit-calc(100% - 30px);
    height:calc(100% - 30px);
}
#x2{width:100%;height:30px;background:yellow;}
</style>
<body>
    <p id="container">
        <p id="x1"></p>
        <p id="x2"></p>
    </p>
</body>
</html>

或者用absolute布局也可以

<html>
<style>
*{margin:0;padding:0;border:0;}
html,body{height:100%}
#container{height: 100%;position: relative;}
#x1{width:100%;background:#CCC;position: absolute;top:0;bottom:30px;}
#x2{width:100%;height:30px;background:yellow;position:absolute;bottom:0;}
</style>
<body>
    <p id="container">
        <p id="x1"></p>
        <p id="x2"></p>
    </p>
</body>
</html>
大家讲道理

第一个考虑兼容性的话使用js的函数比如楼上回答的window.onresize
第二个就是css的@media(这个移动端适配用的多,如果你要写很长的恐怕不划算)

PHPz

布局的话通常让css负责。
你可以看下css的媒体查询功能之类。不知道到答主想要的是不是响应式呢???

巴扎黑

写在浏览器窗口改变事件里,window.onresize = function () {你的代码}

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号