开发者

Moving divs with javascript

开发者 https://www.devze.com 2023-01-13 21:53 出处:网络
This is my problem, I have a div and inside 2 divs, one is centered and the other one is fixed on the left, the problem is when I resize the screen the centered div overlaps the fixed one, what I want

This is my problem, I have a div and inside 2 divs, one is centered and the other one is fixed on the left, the problem is when I resize the screen the centered div overlaps the fixed one, what I wanted to do is detect when the centered div overlaps the other div and change its left value with javascript, but is not working, any ideas?

This is my design:

<div id="content-wrap">
    <div id="content">
    </div>
    <div id="leftbar">
    </div>
</div&开发者_C百科gt;

and the 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;
}

and this is the javascript code:

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';
            }            
    }
}

Thanks in advance for any help.


The easiest fix would be to apply a min-width to your #content-wrap container that prevented the overlap from occurring:

#content-wrap {
    clear: both;
    float: left;
    width: 100%;

    /* #leftbar width x 2 + #content width */
    min-width: 1160px;
}

However, if you want to use Javascript, you'll need to attach the code to the window load and resize events:

$(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
        });
    }
});

The last change you'll need to apply to get this working is to set #content to position: relative in the CSS so it respects the left property you're setting with Javascript:

#content {
    position: relative;
    /* remaining css */
}

You can see it in action here.

0

精彩评论

暂无评论...
验证码 换一张
取 消