简体   繁体   中英

Animate a div out of window/view with jQuery, css rules ignored on resize

I have an absolute positioned div positioned as follows:

#myDiv {
position: absolute;
top: 0%;
height: 500px;
}

@media screen and (max-width: 768px){

#myDiv {
top: 200%;
}

}

The idea being that it is out of the view below 768px window width.

I animate the div into view with jQuery animate with a button when the window width < 768px:

$('#myDiv').animate({
top: "0%"
},350);

I then animate it back out of the view with another button, again when window width < 768px:

$('#myDiv').animate({
    top: "200%"
    },350);

If #myDiv has been animated out of the view (top:200%) and I resize the window above 768px width, the css rule top:0% is ignored. Why?

It's not being ignored, but rather over-written. This is because jQuery's animate function modifies the inline style of the element which takes precedence over any css rules.

the !important modifier in css will tell your inline-style to not take precedence.

top: 0% !important;

However this won't work because it will also overwrite top: 200% in your animate function.

You could listen for matchMedia changes.

Or you could simply handle the animation by toggling classes instead.

@media screen and (max-width: 768px){
  #myDiv {
    top: 200%;
    transition: top 0.35s
  }

  #myDiv.visible {
    top: 0%
  }
}

JS:

$('#myDiv').addClass('visible')

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