Изменить изображение при прокрутке

Я хотел бы изменить изображение в определенной позиции прокрутки. Например:

Прокрутить на 100px показать img1.jpg

Прокрутить на 200px показать img2.jpg

Прокрутите 300px показать img3.jpg

Здесь я нашел пример того, что я имею в виду.

Есть идеи?


person l00per    schedule 16.06.2014    source источник
comment
возможный дубликат Как изменить фон при прокрутке с помощью CSS?   -  person Tanner    schedule 16.06.2014


Ответы (3)


Вы можете использовать событие onScroll для прослушивания прокрутки, проверки положения полосы прокрутки и изменения изображения или всего, что душе угодно. Подробнее о событии onScroll можно прочитать здесь. Базовый код будет примерно таким:

var onScrollHandler = function() {
  var newImageUrl = yourImageElement.src;
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop > 100) {
     newImageUrl = "img1.jpg"
  }
  if (scrollTop > 200) {
     newImageUrl = "img2.jpg"
  }
  if (scrollTop > 300) {
     newImageUrl = "img3.jpg"
  }
  yourImageElement.src = newImageUrl;
};
object.addEventListener ("scroll", onScrollHandler);

Конечно, yourImageElement следует заменить на элемент изображения, который вы хотите изменить.

Если у вас есть jQuery, вы можете использовать метод .scroll() вместо прослушивателя событий и .scrollTop(), чтобы получить положение полосы прокрутки.

Кроме того, вы можете взглянуть на некоторые библиотеки прокрутки/паралекса, такие как skrollr.

person Lior    schedule 16.06.2014

$(window).on("scroll touchmove", function() 
{
	if ($(document).scrollTop() >= $("#one").position().top && $(document).scrollTop() < $("#two").position().top  ) 
	{
		$('body').css('background-image', 'url(https://4.bp.blogspot.com/-Ivk46EkgQfk/WWjbo4TdJbI/AAAAAAAAFUo/gUD7JABklsIA1gWIr5LS1slyY4QuTMkEwCLcBGAs/s1600/gambar%2Bwallpaper%2Bmobil.jpg)')
    };
	if ($(document).scrollTop() >= $("#two").position().top && $(document).scrollTop() < $("#three").position().top)
	{
		$('body').css('background-image', 'url(https://i1.wp.com/cdn.catawiki.net/assets/marketing/uploads-files/45485-8bdcc8479f93d5a247ab844321b8b9d5e53c49a9-story_inline_image.jpg)')
    };
   if ($(document).scrollTop() >= $("#three").position().top && $(document).scrollTop() < $("#four").position().top ) 
   {
		$('body').css('background-image', 'url(https://s-media-cache-ak0.pinimg.com/originals/e1/7a/03/e17a0385726db90de1854177d4af2b4f.jpg)')
   };
   if ($(document).scrollTop() >= $("#four").position().top) 
   {
		$('body').css('background-image', 'url(https://www.wallpaperup.com/uploads/wallpapers/2015/02/13/621414/6fc33c3ae65a58f9bb137f5cf011aebc.jpg)')
   };
  
});
*{
	margin:0;
	padding:0;
 }
.main{
	width:100%;
	height:100vh;
	background-image:url('https://4.bp.blogspot.com/-Ivk46EkgQfk/WWjbo4TdJbI/AAAAAAAAFUo/gUD7JABklsIA1gWIr5LS1slyY4QuTMkEwCLcBGAs/s1600/gambar%2Bwallpaper%2Bmobil.jpg');
	background-size:100% 100%;
	background-attachment:fixed;
	transition: 1000ms;
	}
section{
	width: 100%;
	min-height: 1px;
	}
.content{
	width:50%;
	min-height:1px;margin-top:10%;
	margin-left:10%;
	color:white;
	}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body class='main'>
	<section id="one">
		<div class='content'>
			<h1 style='font-size:5vw;'>first heading</h1>
			<p style='font-size:3vw;' >description</p>	
		</div>
	</section>
	<section id="two" style='margin-top:100vh'>
		<div class='content'>
			<h1 style='font-size:5vw;'>second heading</h1>
			<p style='font-size:3vw;'>description</p>	
		</div>
	</section>
	<section id="three" style='margin-top:100vh' >
		<div class='content'>
			<h1 style='font-size:5vw;'>third heading</h1>
			<p style='font-size:3vw;'>description</p>	
		</div>	
	</section>
	<section id="four" style='margin-top:100vh' >
		<div class='content' style='margin-bottom:10%;'>
			<h1 style='font-size:5vw;'>fourth heading</h1>
			<p style='font-size:3vw;'>description</p>	
		</div>
	</section>
</body>
</html>

документация

create a web folder first.
create a img sub folder  // place  all images into this folder
now create three files // in web folder
index.html 
css.css
js.js 

copy code given bellow and paste it.
save the program.
finally run the program 

Нажмите на эту ссылку, чтобы посмотреть видео:https://www.youtube.com/watch?v=V97wCVY_SrQ
Посетите наш веб-сайт для получения полной документации:https://nozzons.blogspot.com/

index.html

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href='css.css' rel='stylesheet' type='text/css'/>
    <script src='js.js'></script> 
</head>
<body class='main'>
    <section id="one">
        <div class='content'>
            <h1 style='font-size:5vw;'>first heading</h1>
            <p style='font-size:3vw;' >description</p>  
        </div>
    </section>
    <section id="two" style='margin-top:100vh'>
        <div class='content'>
            <h1 style='font-size:5vw;'>second heading</h1>
            <p style='font-size:3vw;'>description</p>   
        </div>
    </section>
    <section id="three" style='margin-top:100vh' >
        <div class='content'>
            <h1 style='font-size:5vw;'>third heading</h1>
            <p style='font-size:3vw;'>description</p>   
        </div>  
    </section>
    <section id="four" style='margin-top:100vh' >
        <div class='content' style='margin-bottom:10%;'>
            <h1 style='font-size:5vw;'>fourth heading</h1>
            <p style='font-size:3vw;'>description</p>   
        </div>
    </section>
</body>
</html>

css.css

*{
    margin:0;
    padding:0;
 }
.main{
    width:100%;
    height:100vh;
    background-image:url('img/img_one.jpg');
    background-size:100% 100%;
    background-attachment:fixed;
    transition: 1000ms;
    }
section{
    width: 100%;
    min-height: 1px;
    }
.content{
    width:50%;
    min-height:1px;margin-top:10%;
    margin-left:10%;
    color:white;
    }

js.js

$(window).on("scroll touchmove", function() 
{
    if ($(document).scrollTop() >= $("#one").position().top && $(document).scrollTop() < $("#two").position().top  ) 
    {
        $('body').css('background-image', 'url(img/img_one.jpg)')
    };
    if ($(document).scrollTop() >= $("#two").position().top && $(document).scrollTop() < $("#three").position().top)
    {
        $('body').css('background-image', 'url(img/img_two.jpg)')
    };
   if ($(document).scrollTop() >= $("#three").position().top && $(document).scrollTop() < $("#four").position().top ) 
   {
        $('body').css('background-image', 'url(img/img_three.jpg)')
   };
   if ($(document).scrollTop() >= $("#four").position().top) 
   {
        $('body').css('background-image', 'url(img/img_four.jpg)')
   };

});
person sanjay oraon    schedule 06.11.2018

Итак, я просто отвечаю на эту старую тему, потому что я пытался реализовать то же самое на своем веб-сайте, но мне было немного сложно реализовать это, поэтому я сделал собственную функцию, ее немного проще реализовать и понять, но немного глючит, например: если пользователь использует полосу прокрутки вместо колеса прокрутки мыши, изображение не изменится, надеюсь, это поможет вам:

<html>

<head>
  <script>
    function f() {
      t1.src = "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg"
      t1.height = "319"
      t1.width = "330"
    }

    function f2() {
      t1.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG"
      t1.height = "319"
      t1.width = "330"
    }

    function f3() {
      t1.src = "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg"
      t1.height = "244"
      t1.width = "330"
    }

    function f4() {
      t1.src = "https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg"
      t1.height = "244"
      t1.width = "350"
    }

    function f5() {
      t1.src = "http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"
      t1.height = "319"
      t1.width = "350"
    }
  </script>
</head>

<body>
  <div align="center" style="position: fixed; z-index: 20; left:38.5%; top:200">
    <img src="no.png" height="319" width="330" name="t1">
  </div>
  </div>
  <div class="container" onmouseover="f3()" style="padding:0; margin:0; width:100%;">
    <img src="https://pixabay.com/static/uploads/photo/2016/01/11/22/05/background-1134468_960_720.jpg" width="100%">
  </div>
  <br>
  <br>
  <div class="container" onmouseover="f4()" style="padding:0; margin:0; width:100%;">
    <img src="https://image.freepik.com/free-photo/lens-flare-abstract-backgound_21276999.jpg" width="100%">
  </div>
  <br>
  <br>
  <div class="container" onmouseover="f5()" style="padding:0; margin:0; width:100%;">
    <img src="https://image.freepik.com/free-photo/lens-flare-abstract-backgound_21276999.jpg" width="100%">
  </div>
  <br>
  <br>
  <div class="container" onmouseover="f()" style="padding:0; margin:0; width:100%;"></div>
</body></html>
Cheers!! Ha[ppy] Coding.

person Suyash Doneria    schedule 07.09.2016