简体   繁体   English

CSS 在视口中使用 DIV 时更改背景颜色

[英]Change CSS background color when DIV in viewport

is it possible to change the background color of my website when a specific div is in the viewport?当特定的 div 在视口中时,是否可以更改我网站的背景颜色? And would it be possible to change the background color again (ie for the 2nd time) if another DIV is in the viewport?如果另一个 DIV 在视口中,是否可以再次更改背景颜色(即第二次)?

So something like this:所以像这样:

BLUE BLUE BLUE ... DIV1 (in the viewport = background color RED) RED RED RED ... DIV2 (in the viewport = background color BLUE) BLUE BLUE BLUE BLUE BLUE BLUE ... DIV1(在视口中 = 背景色 RED) RED RED RED ... DIV2(在视口中 = 背景色 BLUE) BLUE BLUE BLUE

Many thanks in advance!提前谢谢了!

Explanation解释

"When the user scrolls to the TOP of the blue div, the background color of the body changes to red." “当用户滚动到蓝色 div 的顶部时,主体的背景颜色变为红色。”

 $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll >= $('#blue').offset().top) { $('body').css('background-color', 'red'); } if (scroll >= $('#black').offset().top) { $('body').css('background-color', 'blue'); } if (scroll >= $('#black').last().offset().top) { $('body').css('background-color', 'green'); } });
 #blue { width: 400px; height: 800px; background: blue; } #black { width: 400px; height: 800px; background: black; } #red { width: 400px; height: 800px; background: red; margin-bottom: 500px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="blue"></div> <div id="black"></div> <div id="red"></div>

you can always call that on the media query to change anything you want at particular height or color heres an example if i understand you right你总是可以在媒体查询中调用它来改变你想要的任何在特定高度或颜色的东西,如果我理解你的话,这是一个例子

 body {background-color:gray;}.mygridboxes { display:grid; }.box { height:500px; width:500px; background-color:red; font-size:50px; text-align:center; margin:0 auto; border:10px solid white; } @media only screen and (max-width:1024px){ body { background-color:yellow; }.box { background-color:green;//change background height:350px; //resize height width:350px;} } @media only screen and (max-width:768px){ body { background-color:yellow; }.box { background-color:green;//change background height:300px; //resize height width:300px;} } @media only screen and (max-width:479px){ body {background-color:blue;}.box { background-color:pink;//change background height:200px; //resize the height here width:200px; } }
 <body> <h1>RESIZE ME</h1> <div class="mygridboxes"> <div class="box">A</div> <div class="box">B</div> <div class="box">C</div> <div class="box">D</div> </div> </body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM