When scrolling down the page, the block changes the property when it is already at the top of the screen. And how to make the property change when the unit is located in the center of the vertical screen?

$(function() { var person = $('.person'); person.css({ 'margin-left': '300px' }); $(window).on('scroll', function(e) { var h = ($(window).height() - person.height()) / 2; $('.person').each(function() { if ($(window).scrollTop() + $(this).height() > $(this).offset().top) { $(this).css({ 'margin-left': '10px' }); } else { $(this).css({ 'margin-left': '300px' }); } }); }); }); 
 .person { margin-left: 10px; transition: margin-left .4s; } p { height: 700px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p></p> <div class="person"><img alt="" src="https://i02.fotocdn.net/s16/240/gallery_xs/254/54328815.jpg"></div> <p></p> <div class="person"><img alt="" src="https://i02.fotocdn.net/s16/240/gallery_xs/254/54328815.jpg"></div> <p></p> <div class="person"><img alt="" src="https://i02.fotocdn.net/s16/240/gallery_xs/254/54328815.jpg"></div> <p></p> <p></p> 

    1 answer 1

    You can try this code. As soon as the element is in the middle of the page, the style will be applied.

      $(function() { var person = $('.person'); person.css({ 'margin-left': '250px' }); $(window).on('scroll', function(e) { $('.person').each(function() { /** Получить середину длины экрана */ var windowVertivalCenterPosition = $(window).width() / 2; /** Получить середину изображения. То есть взять позицию изображения и прибавить к середине изображения */ var imageReleativePosition = $(this).offset().left + ($(this).width() / 2); /** Если нужно полить точно вертикальное совпадение по середине */ if (windowVertivalCenterPosition - imageReleativePosition == 0) { $(this).css({ 'margin-left': '10px' }); } }); }); }); 
     .person { margin-left: 10px; transition: margin-left .4s; } p { height: 700px; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p></p> <div class="person"><img alt="" src="https://i02.fotocdn.net/s16/240/gallery_xs/254/54328815.jpg"></div> <p></p> <div class="person"><img alt="" src="https://i02.fotocdn.net/s16/240/gallery_xs/254/54328815.jpg"></div> <p></p> <div class="person"><img alt="" src="https://i02.fotocdn.net/s16/240/gallery_xs/254/54328815.jpg"></div> <p></p> 

    But I do not know whether to use the exact coincidence in the middle - especially during scrolling? At least if you need a more stringent mid-match check, you can use this check instead of the one above.

     /** Если нужно полить вертикальное совпадение по середине +- 100px */ if (windowVertivalCenterPosition - imageReleativePosition < 200 && windowVertivalCenterPosition - imageReleativePosition > -200) { $(this).css({ 'margin-left': '10px' }); } 
    • Thanks for the help! - LADYX