简体   繁体   中英

Jquery event capture change in margin-left

I have a situation in here I have a div that was margin: auto to get it to be centered.

That works fine, but when I resize the window I want it to stop centering when a certain margin-left is reached.

The ideia is that I have a floating object to the left, and I dont want it to be overlapped.

Anybody as a suggestion?

Thanks

EDIT : Code Addded

<nav id="servicos_nav">
    <div id="full">
        ...
    </div>
    <div id="minimized">
        ...
    </div>
</nav>
<section id="content">
… PHP generated code …
</section>

The nav is absoluted possitioned because it was some effects, changind minimized by full with animations.

Section content as width of 860px and margin auto. But there is and element in the nav that always as 140px width and I dont want that minimizing the window causes the content to overlap with that element.

SolutionEdit : My solution based on the awnser (the static width was just easier :-) ):

window.onresize = function(event) {
        if(window.innerWidth <= 1142)
        {
            $("#content").css("margin-left","140px");
        }
        else
        {
            $("#content").removeAttr("style");
        }
    };

You may have to work on the math as this is not my strong point but something like this should work

var contentWidth = $('#content').width();
var leftWidth = $('#left').width();

$(window).resize = function(event) {
    var windowWidth = window.innerWidth;
    if (windowWidth <= (contentWidth + (leftWidth * 2)) {
        $('#content').css('margin-left', leftWidth);
    } else {
        $('#content').css('margin-left', 'auto')
    }
}

demo

Edit: changed to use jQuery .resize rather then override onresize

You could use the offset of #content.

$(window).resize = function(event) {
   if ($('#content').offset().left < leftWidth) {
     $('#content').css('margin-left', leftWidth);
   } else {
     $('#content').css('margin-left', 'auto')
   }
}

elements that have margin 0px auto don't have an accessible margin left. That means an element with margin: 0px auto will have margin-left and margin-right equal to 0.

The solution lies in CSS, not in Javascript. You could, and should rethink your layout. Here, this is a way of doing it with css min width .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM