繁体   English   中英

在 div 上向左或向右移动鼠标时迭代数组

[英]Iterate over Array on mouse move left or right over a div

我有一个静态的字符串数组和一个包含 ap 元素的 div,该元素一次包含一个字符串。 我试图做的是当您在 div 上移动时,您遍历数组并根据当前鼠标位置以及数组中的位置更改文本。

我想这样做的方式是

  1. 以像素为单位获取 div 大小,将其除以数组中的元素数量。

  2. 然后我会在每次更改时检查鼠标位置,并根据其位置(例如在 div 的 52 部分)将其更改为数组中的 52 项。

我是不是想多了? 有没有更简单的方法来做到这一点?

类似下面的解决方案应该适合你。 为要添加的每个字符串添加您选择的 div/span/container。 添加一个事件侦听器,在鼠标移入时显示字符串的容器,并在鼠标移出时删除事件侦听器。 我们使用 'visibility: hidden' 而不是 'display: none' 来确保你的包含块仍然存在于 DOM 中。

索引.html:

    <div class="container">
    </div>

主文件:

    .container {
      display: flex;
      flex-direction: row;
      background: #DDD;
      width: 100%;
      height: 200px;
    }

    .child {
      width: 100%;
      height: 100%;
      color: black;
    }

    .hide {
      visibility: hidden;
    }

索引.js:

         //Replace this with however you're getting your strings now
        var stringContent = ["String #1", "String #2", "String #3"]

        $(document).ready(function(){

          //You can remove this if the number of strings are not dynamic and replace with the hardcoded html tags
          for (var i = 0; i < stringContent.length; i++)
            {
              var eleToAdd = `<div class='child hide'>${stringContent[i]}</div>`
              $(".container").append(eleToAdd)
            }

          $(".child").on("mouseenter", function(){
            $(this).removeClass("hide");
          })

          $(".child").on("mouseout", function(){
            $(this).addClass("hide");
          })
        })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM