这是我的问题,我有一个 div,里面有 2 个 div,一个居中,另一个固定在左侧,问题是当我调整屏幕大小时,居中的 div 与固定的 div 重叠,我想要的做的是检测居中的 div 何时与另一个 div 重叠并使用 javascript 更改其左侧值,但不起作用,有什么想法吗?
这是我的设计:
<div id="content-wrap">
<div id="content">
</div>
<div id="leftbar">
</div>
</div>
和CSS:
#content-wrap
{
clear: both;
float: left;
width: 100%;
}
#content
{
text-align: left;
padding: 0;
margin: 0 auto;
height: 470px;
width: 760px;
overflow: auto;
}
#leftbar
{
background-color: transparent;
width: 200px;
height: 470px;
position: absolute;
top: 185px;
left: 50px;
}
这是javascript代码:
window.onload = function Centrar() {
var leftBar = $get("leftbar");
if (leftBar != null) {
var content = $get("content");
var size = leftBar.offsetLeft + leftBar.offsetWidth;
if (content.offsetLeft < size) {
content.style.left = size + 20 + 'px';
}
}
}
在此先感谢您的帮助。
最佳答案
最简单的解决方法是应用 min-width到防止重叠发生的 #content-wrap
容器:
#content-wrap {
clear: both;
float: left;
width: 100%;
/* #leftbar width x 2 + #content width */
min-width: 1160px;
}
但是,如果您想使用 Javascript,则需要将代码附加到窗口加载和调整大小事件:
$(window).bind('load resize', function() {
var content = $('#content');
var leftbar = $('#leftbar');
// get the right edge of the #leftbar
var leftbarEdge = leftbar.width() + leftbar.offset().left;
// check if an overlap has occured and adjust #content left position if yes
if (leftbarEdge > content.offset().left) {
content.css({
left: leftbarEdge - content.offset().left
});
}
});
要使此工作正常进行,您需要应用的最后一个更改是在 CSS 中将 #content
设置为 position: relative
,以便它尊重 left
您使用 Javascript 设置的属性:
#content {
position: relative;
/* remaining css */
}
可以看到in action here .
关于javascript - 使用javascript移动div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3600195/