简体   繁体   中英

Iterate over Array on mouse move left or right over a div

I have an static Array of Strings and a div that contains ap element that contains one string at a time. What im trying to do is when you move across the div, you iterate over the array and change your text based on the current mouse position and thus position in the array.

The way i thought of doing this was

  1. Getting div size in pixels, dividing this by the amounts of elements in the array.

  2. Then i would check the mouseposition every time it changes and depending on its position (eg in the 52 section of the div) would change it to the 52 item in the array.

Am i overthinking this? Is there an easier way to do this?

Something like the solution below should work for you. Add a div/span/container of your choice for each string you want to add. Add an event listener that shows your string's container when you mouse-in, and removes the event listener when you mouse out. We use 'visibility: hidden' instead of 'display: none' to make sure your containing blocks still exist in the DOM.

Index.html:

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

Main.css:

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

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

    .hide {
      visibility: hidden;
    }

Index.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");
          })
        })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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