繁体   English   中英

当另一个div在视口中时,更改固定div中显示的图像

[英]Change image shown in fixed div when another div is in viewport

我有一个固定的div,其中包含一张与用户一起从页面顶部滚动的图片。 当新的内容div进入视口时,我要更改图像。

我找到了一段相关的代码,该代码将根据用户滚动像素的距离来更改图像。 这有效,但仅当视口为特定大小时,否则图像更改得太早/太晚:

我正在尝试修改此设置,以使更改改为基于何时显示另一个div,以便无论屏幕大小如何(内容div的高度均以相对单位设置)都可以使用。 我认为,如果将其他div位置保存到变量中,然后代替上面代码中的像素值,则可以完成此操作。 但是我似乎无法正确地做到这一点,可能是因为我没有正确计算其他div位置。

 $("#display1").fadeIn(1000); $(window).scroll(function() { var pos = $(window).scrollTop(); var first = $("#first").offset(); var second = $("#second").offset(); if (pos < first) { hideAll("display1"); $("#display1").fadeIn(1000); } if (pos > first && pos < second) { hideAll("display2"); $("#display2").fadeIn(1000); } etc... }); function hideAll(exceptMe) { $(".displayImg").each(function(i) { if ($(this).attr("id") == exceptMe) return; $(this).fadeOut(); }); } 

你应该试试

getBoundingClientRect()

JS方法,因为它获取元素相对于视口的位置。 检查此答案: https : //stackoverflow.com/a/7557433/4312515

这是一个基于元素进入背景更改背景图像的概念的快速证明。

有三个div。 当第三个div到达视口的底部时,它将更改背景的颜色。 当第三个div再次从视图中滚动出时,背景颜色将重置为其初始颜色。

通常,您应该消除滚动事件的抖动,以防止降低UI速度。 在此示例中,我没有对事件进行防抖操作,因此您可以更好地了解何时更改了背景。

 const card3 = document.getElementById('card3'), background = document.getElementById('background'); let isCardVisible = false; function checkDivPosition() { const cardTopPosition = card3.getBoundingClientRect().top, viewportHeight = document.documentElement.clientHeight, isInView = cardTopPosition - viewportHeight < 0; if (isInView && !isCardVisible) { background.style.backgroundColor = 'rebeccapurple'; isCardVisible = true; } else if (!isInView && isCardVisible) { background.style.backgroundColor = 'orange'; isCardVisible = false; } } function onWindowScroll(event) { checkDivPosition(); } window.addEventListener('scroll', onWindowScroll); 
 body { margin: 0; } .background { height: 100vh; opacity: .2; position: fixed; transition: background-color .3s ease-out; width: 100vw; } .card { border: 1px solid; height: 100vh; width: 100vw; } .card + .card { margin-top: 5vh; } 
 <div id="background" class="background" style="background-color:orange"></div> <div class="card"> Card 1 </div> <div class="card"> Card 2 </div> <div id="card3" class="card"> Card 3. </div> 

暂无
暂无

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

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