[英]Css - how to change element size if it reached to certain spot on screen?
I've dynamically created some divs with random color who are scattered over the page randomly. 我已经动态地创建了一些随机颜色的div,这些div随机分散在页面上。 I want to use css to give them a condition that says that if the div is located above let's say 600px on the screen - his size will change.
我想用css给他们一个条件,说如果div位于上面让我们说屏幕上600px - 他的大小会改变。 I know the "if" statement for css is @media but I didn't figure how to use it right in this situation.
我知道css的“if”语句是@media但我没有想到如何在这种情况下正确使用它。 Can you help me?
你能帮助我吗?
Example of a div (they all have the same class - "frog") div的例子(它们都有相同的类 - “青蛙”)
<div id="frog" class="fas fa-ad" style="width: 66px; height: 66px;
background-color: rgb(87, 58, 55); position: absolute; left: 312px; top:
93px; display: block;"></div>
You can't do that with CSS only. 你不能只用CSS做到这一点。 The only way you can have dynamic styling based on what happens in the windows in CSS is to use media queries.
根据CSS中窗口中发生的事情,您可以拥有动态样式的唯一方法是使用媒体查询。 However, the docs precise that you can only detect window-level data , like the device width, or whether the page is displayed on a screen or on a printed paper, etc.
但是, 文档确切地说您只能检测窗口级数据 ,例如设备宽度,或者页面是显示在屏幕上还是打印在纸上等。
You'll have to change your style with JS. 你必须用JS改变你的风格。 This is often a bad way to have dynamic styling, because the only way to do so is to 'probe' the DOM (using for example
setInterval
). 这通常是动态样式的一种不好的方法,因为这样做的唯一方法是“探测”DOM(使用例如
setInterval
)。 Luckily your case is an exception - since you update your divs position with JS, you can check directly after that the position of your divs, and update your styles accordingly! 幸运的是你的情况是一个例外 - 因为你用JS更新你的div位置,你可以直接检查你的div的位置,并相应地更新你的样式!
Example using the very useful getBoundingClientRect : 使用非常有用的getBoundingClientRect的示例:
// select the frog element let frog = document.getElementById('frog'); let count = 0; setInterval(() => { // update the frog position frog.style.top = `${count}px`; count = (count+2)%200; // check if the frog is after 100px from the top of the window if (frog.getBoundingClientRect().top>100) { frog.className = 'over-100'; } else { frog.className = ''; } }, 1000/30);
#frog { position: fixed; top: 0; left: 0; width: 50px; height: 50px; background-color: green; } #frog.over-100 { background-color: olive; }
<div id="frog"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.