![](/img/trans.png)
[英]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.