Change margin-top to scroll

I have a negative margin on the div, but I want to change the negative margin on the scroll until the negative value reaches 0.

from

margin:-150px 0 0 0; 

to: (scroll)

 margin:0px 0 0 0; 

I think this is some kind of parallax effect where I search and find this in StackOverflow: Change the top border of the div field based on the scroll of the window

I was thinking about something like this, but it should be something easier

 $(window).scroll(function(){ if ($(window).scrollTop() >= 1){ $('#three').css({margin:'-149px 0 0 0px'}); } if ($(window).scrollTop() >= 2){ $('#three').css({margin:'-148px 0 0 0px'}); } if ($(window).scrollTop() >= 3){ $('#three').css({margin:'-147px 0 0 0px'}); } if ($(window).scrollTop() >= 4){ $('#three').css({margin:'-146px 0 0 0px'}); } else { $('#three').css({margin:'-150px 0 0 0px'}); } }); 

-

I created a script with the html / css base

fiddle: http://jsfiddle.net/qSe4e/

-

Thank you so much for the advanced

+6
source share
2 answers

Try using a little math to automatically generate all the possibilities (similar to your attempt, but with one line instead of one for each opportunity.

Example: http://jsfiddle.net/qSe4e/9/

 $(window).scroll(function(){ var fromTop = $(window).scrollTop(); $("#three").css('margin', '-' + (100 - fromTop) + 'px 0px 0px 0px'); }); 
+7
source

Do it like this:

 $(document).scroll(function () { $("#three").animate({margin: "0px 0px 0px 0px"}, 3000); }); 

Demo script

+1
source

Source: https://habr.com/ru/post/955650/


All Articles