我正在制作这个简单的元素,当我将鼠标悬停在 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);
});
关于javascript - 如何停止javascript增量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56720535/