[英]How to make dropdown menu disappear after a certain amount of time JavaScript
[英]How to make a div disappear after a certain distance using condition "if" (JavaScript)
我试图将一个块移动到右侧 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>
但我添加了一个 IF:如果它超过 200 像素,它应该会消失。 问题是不管像素如何,它都会消失。
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>
我的条件:
if(document.getElementById("blue").style.transform = "translate(200px)" > "200px")
好像错了,怎么写?
首先我们 select 元素并存储元素的当前 position。 然后我们设置一个监听ontransistioned()
,它在元素的转换发生后被触发。 当监听器 function 被触发时,我们确定旧的 position 和新的 position 之间的区别。 如果这个差值大于等于 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.