简体   繁体   中英

Changing CSS Upon Window Resizing Breaks CSS

How to recreate:

As you can see your able to increase the size of the grey box by hovering your mouse over it.

  • Resize the width of the tab to the smallest it will go (the grey box will disappear)
  • Resize back to how it was before and now the CSS :hover will no longer work.

Annoyingly I can fix it buy changing the javascript code:

$(document).ready(function () {
    $(window).resize(function(){

        if ($(window).width() < 640) {
            $('.content').css({
                'width': '100%',
                    'left': '0px'
            });
            $('.menu-button img').attr('src', 'test/lines.png').load(function () {
                this.width;
            });
        }
    if ($(window).width() > 640) {
            $('.content').css({
                'width': 'calc(100%-50px)',
                    'left': '50px'
            });
        }

    });//<-- removing this

Breaking the code and having an open bracket obviously isn't wanted as a fix and causes problem with the rest of my javascript.

Why does it act differently after changing the css back to exactly what it was using JQuery/Javascript?

The issue is when you resize back, this line:

$('.content').css({
    'width': 'calc(100%-50px)',
    'left': '50px'
});

is setting the class content style to:

left: 50px;
width: 100%;

The left: 50px is what's breaking the behavior, and since it's a style tag, it will always override the css tags. If you change this to remove the left when you drag the gray box back over 640px, it will work. See the fiddle here: https://jsfiddle.net/y408c0u9/8/

However, I would recommend you use media queries in css to do this. Javascript can be tough to maintain responsive behavior in, and you can do this in css.

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