简体   繁体   中英

Dynamically toggle class based on div's width

So I have a container with content and two side drawer (left/right) that when open, they squeeze the content width.

<div class="container">
    <div">sidepanel-left</div>
    <div class="content">content</div>
    <div>sidepanel-right</div>
</div>

For example: when both sidepanel-left and right are close, the "content" div is 1000px width. When one sidepanel is open, the "content" div is pushed to 800px because sidepanel are 200px width. When both sidepanel are open, then the "content" div is 600px.

I would like a script that adds/removes a class ".small" dynamically to the "content" div when it's smaller/bigger than 700px.

That way, if you open or close any or both sidepanel, the "content" div will receive it's class ".small" without resizing the window or reloading the page.

I will use that class to hide/show other div inside "content" div.

I have tried this plugin ( http://benalman.com/code/projects/jquery-resize/examples/resize/ ) but it won't dynamically add/remove the class. It adds the class when I open the two sidebar, but if I close one, which makes the div "content" larger than 700px, it won't remove it.

jQuery(document).ready(function($) {    
     $(".content").resize(function() {
        if ($(".content").width() < 700 ) {
           $('.content').addClass('small');
        } else {
            $('.content').removeClass('small');
        }
    });
}); 

Thanks in advance :)

B.

[EDIT]

website is: www.unicyclist.info sidepanels can be activated by clicking the [...] on the top right and left corner. 这是“.content”div的图像(以“.es-content”类命名。

Pretty sure the var is your mistake.

jQuery(document).ready(function($) {    
    $(".content").resize(function() {
        $(this).toggleClass('small', ($(this).width() < 700) );    
    });
}); 

JQuery resize() is only triggered when the browser window changes!

You can create your own function to check if the size of the div has changed:

contentWidth = -1;

function checkForSizeChange() {
    var $content = $('.content'),
        width = $content.width();

    if(contentWidth != width) {
        if(width < 700) {
            $content.addClass('small');
        } else {
            $content.removeClass('small');
        }       
        contentWidth = width;
    }
}

setInterval(checkForSizeChange, 100);

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