首页 > 解决方案 > 如何停止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>

标签: javascripthtmlcss

解决方案


如果您希望 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);
});

推荐阅读