简体   繁体   English

如何使用条件“if”(JavaScript)在一定距离后使 div 消失

[英]How to make a div disappear after a certain distance using condition "if" (JavaScript)

I tried to move a block to 200 px on the right (this part is fine)我试图将一个块移动到右侧 200 px(这部分很好)

 function blue() { document.getElementById("blue").style.transform = "translate(200px)"; document.getElementById("blue").style.transition = "0.5s"; }
 #blue{ width: 200px; height: 200px; margin: 2rem; background-color: rgb(133, 133, 134); }
 <div id="blue"></div> <button onclick="blue()">right</button>

but I add an IF: if it's more than 200 px it should disappear.但我添加了一个 IF:如果它超过 200 像素,它应该会消失。 The problem is that is disappear anyway regardless of the px.问题是不管像素如何,它都会消失。

 function blue() { document.getElementById("blue").style.transform = "translate(200px)"; document.getElementById("blue").style.transition = "0.5s"; if(document.getElementById("blue").style.transform = "translate(200px)" > "200px"){ document.getElementById("blue").style.display = "none"; } else { document.getElementById("blue").style.display = "block"; } } function appear(){ document.getElementById("blue").style.display = "block" }
 #blue{ width: 200px; height: 200px; margin: 2rem; background-color: rgb(133, 133, 134); }
 <div id="blue"></div> <button onclick="blue()">right</button> <button onclick="appear()">make it appears</button>

My condition:我的条件:

 if(document.getElementById("blue").style.transform = "translate(200px)" > "200px")

seems wrong, how can I write it?好像错了,怎么写?

First we select the element and store the current position of the element.首先我们 select 元素并存储元素的当前 position。 Then we set a listener ontransistioned() which is fired after the element's transition has occurred.然后我们设置一个监听ontransistioned() ,它在元素的转换发生后被触发。 When the listener function is fired, we determine the difference between the old position and the new position.当监听器 function 被触发时,我们确定旧的 position 和新的 position 之间的区别。 If this difference is greater equal 200, we set the display property to "none" .如果这个差值大于等于 200,我们将display属性设置为"none"

 function blue() { const elem = document.getElementById("blue"); const oldPos = elem.getBoundingClientRect(); elem.ontransitionend = () => { const newPos = elem.getBoundingClientRect() const diff = Math.abs(oldPos.x - newPos.x) if (diff >= 200) elem.style.display = "none"; }; elem.style.transform = "translate(200px)"; elem.style.transition = "0.5s"; } function appear(){ document.getElementById("blue").style.display = "block" }
 #blue{ width: 200px; height: 200px; margin: 2rem; background-color: rgb(133, 133, 134); }
 <div id="blue"></div> <button onclick="blue()">right</button> <button onclick="appear()">make it appears</button>

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

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