javascript - 如何停止javascript增量?
问题描述
我正在制作这个简单的项目,当我将鼠标悬停在 div 上时,它会展开 div,但我想将此 div 展开到网页末尾并且不想越过网页。
HTML
<div class="center"></div>
CSS
body {
background-color: black;
}
.center {
width: 1%;
transform-origin: right;
height: 20px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: green;
left: 0;
transition: all 0.5s ease;
}
JAVASCRIPT
let div = document.querySelector("div");
let indx = 0;
div.addEventListener("mousemove", e => {
indx++;
div.style.width = indx + "%";
console.log(indx);
if (indx === 200) {
indx = 200;
}
});
</script>
解决方案
如果您希望 200 成为最大值,则必须检查它是否超过 200,然后将其设置为 200
let div = document.querySelector("div");
let indx = 0;
div.addEventListener("mousemove", e => {
indx++;
if (indx > 200) {
indx = 200;
}
div.style.width = indx + "%";
console.log(indx);
});
推荐阅读
- angular - 如何在我的服务中删除事件监听器?
- java - ++i 和 i++ 与 finally{} 之间的 Java 区别
- scala - 如何使用 foreach 拆分 Spark 数据框中的 Json 格式列值
- c# - 隔离 EF Core 中的更改
- php - 如何在php中对sql数据的输出进行排序
- sql - Golang 连接到 Cubrid
- reactjs - 未识别 SignalR 连接的 React 和 SignalR 中的问题
- c - 如何使用此正则表达式避免 regcomp 错误 13?
- c++ - 不向socket.io nodejs(服务器)发出数据socket.io c++(客户端)
- react-native - 想要在 reactNative 的其他组件中显示选定的图像