首页 > 解决方案 > 如何使用条件“if”(JavaScript)在一定距离后使 div 消失

问题描述

我试图将一个块移动到右侧 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")

好像错了,怎么写?

标签: javascript

解决方案


首先我们选择元素并存储元素的当前位置。然后我们设置一个监听ontransistioned()器,在元素转换发生后触发。当侦听器函数被触发时,我们确定旧位置和新位置之间的差异。如果这个差值大于等于 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>


推荐阅读