I have this code
$(document).scroll(function() {
var $window = $(window);
var position = $window.scrollTop();
if(position <= 2950){
$(".lion_head").animate({right: "-100px"}, 2000);
};
});
So if I scroll from 2950px
the .lion_head
will move -100px
from right, What I want is when I scroll down, or scroll up, or when my scroll bar is not on 2950px
, The position of my .lion_head
moves to its original position?
thanks.
Try wrapping your code inside $(window).on('scroll', function(e){ ... });
.
In side the event function, do your animation logic.
$(window).on('scroll', function(e){
var position = $(window).scrollTop();
if(position <= 2950){
$(".lion_head").animate({right: "-100px"}, 2000);
}
else{
$(".lion_head").animate({right: "0"}, 2000);
}
});
See jQuery.scroll for more details.
Use pure javascript
var lionHead = document.querySelector(".lion_head");
window.addEventListener("scroll", function(event) {
this.scrollY <= 2950 ? lionHead.classList.add('fixed') : lionHead.classList.remove('fixed')
}, false);
The Style
.lion_head{transition:all .3s ease}
.fixed{right: -100px}
Here is the full illustration, scroll up and down to see it in action:
var lionHead = document.querySelector(".lion_head"); window.addEventListener("scroll", function(event) { this.scrollY <= 2950 ? lionHead.classList.add('fixed') : lionHead.classList.remove('fixed') }, false);
:root{height: 4000px} .lion_head{ width: 150px; height: 150px; background: orange; position: fixed; top: 60px; right: 80vw; transition:all .3s ease } .fixed{right: -100px}
<div class=lion_head></div>
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.