【发布时间】:2014-12-23 23:52:16
【问题描述】:
我使用这个 javascript 来根据内容使 2 个 div 具有相同的高度。 但是,当我使屏幕变小时,div 1 的内容会低于 div 2(尝试过 IE 和 FF)。换句话说 div 1 不会拉伸。但是,当我更改屏幕尺寸并使其变小时,div 确实会拉伸。当我刷新屏幕尺寸低于 1024 像素的 div 并调整它的大小时,它会拉伸,直到我再次将屏幕尺寸设置为高于 1024 并低于 1024。
这一切都有些模糊(也许),但我制作了这个视频来清除问题:https://www.youtube.com/watch?v=lxe7Lr4Jt0s 也可以在这里看到它:http://jsfiddle.net/evvwhosz/ 或在这里:http://goo.gl/41IRWm
我发现 javascript 导致了这种情况,因此我试图在屏幕大小调整到 1024 像素以下时删除 javascript(边距),但到目前为止它不起作用。正如您所看到的,我确实付出了一些努力来陈述我的问题;)这是因为我已经在寻找解决方案了这么久。请问,谁能帮帮我?
代码如下:
<html>
<head>
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<script>
function handleMargins() {
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
if(width > 1024) {
setTimeout(function(){
var lcol_height = $("#leftCol2").height() + 0; // add 80 for margin + padding
var rcol_height = $("#rightCol2").height();
if(rcol_height > lcol_height) $("#leftCol2").css('height',(rcol_height - 0) + 'px');
else $("#rightCol2").css('height',lcol_height + 'px');
}, 500);
}
else {
return false;
}
}
jQuery(document).ready(handleMargins);
$(window).resize(handleMargins);
</script>
<style>
body{ background:#f6f6f6;}
#container2 {
width: 926px;
width:100%;
}
#leftCol2{ float:left;
width: 300px;
background:#FFFFFF;
}
#rightCol2{ float:left;
width:300px;
background: #FF9;
}
@media only screen and (max-width: 1024px) {
#leftCol2{float:left;
width:100%;
}
#rightCol2{float:left;
width:100%;
}
}
</style>
</head>
<body>
<div id="container2">
<div id="leftCol2">
<p>This div is longer than the right one. This div is longer than the right one. This div is longer than the right one. This div is longer than the right one. This div is longer than the right one. This div is longer than the right one.</p>
<p>This div is longer than the right one. This div is longer than the right one. This div is longer than the right one. This div is longer than the right one. This div is longer than the right one. This div is longer than the right one.LAST</p>
</div>
<div id="rightCol2">
<p>Div 2.</p>
</div>
</div>
</body>
</html>
【问题讨论】:
-
您是否有理由不使用普通 CSS 来解决这个问题?这是某种实验吗?
-
@MathijsSegers 它们是两列,它们的高度似乎相互依赖;作为一项规则,CSS 往往不允许格式依赖于先前的元素。也就是说,用 JS 解决这个问题也有风险。
-
嗨,我需要 div 的高度相同。有人告诉我,当浮动 div 时,很难让它工作。我尝试了 display:table,它可以工作,但并非所有浏览器都支持它,而且我在交换 div 时遇到了一些问题(使用 js,'order' 不经常支持),请参阅:stackoverflow.com/questions/27602681/…。这就是为什么我正在寻找浮动 div 的解决方案。
-
除了浮动,你还可以使用 display:inline-block。
-
您是否尝试过在 div 之间划分宽度 var divWidth = Math.floor($('#container2').width() / 2); $('#leftCol2').css({width : divWidth}); $('#rightCol2').css({width : divWidth});
标签: javascript resize margin