javascript - 如何使用条件“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")
好像错了,怎么写?
解决方案
首先我们选择元素并存储元素的当前位置。然后我们设置一个监听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>
推荐阅读
- javascript - 带有方法的属性的 Javascript 对象文字
- ruby-on-rails - Ruby on Rails 中多种类型用户的最佳实践是什么
- mocha.js - 使用 Typescript 编写的使用 NYC/Istanbul 的 Fastify 集成测试没有代码覆盖
- symfony - 使用 symfony/messenger 时切换 symfony/mailer 中的 sendmail 参数
- python - 从图像中去除噪声而不丢失 OpenCV 中的数据
- android - Invariant Violation:WebView 已从 React Native 中移除
- javascript - 尽管我使用了加载事件,img.height 随机返回 0
- flutter - 检测 TextFormField 停止输入颤动
- svelte - 为什么它不知道相同的内容?
- asp.net-core - 单击 blazor 中的按钮时如何动态添加新的输入字段