简体   繁体   中英

Show image when hovering over dropdown created dynamically

I have seen many posts where once you hover over an item in the dropdown bar, you can see an image. But all of these posts have coded the items in the dropdown into the html. I am dynamically creating the dropdown items using javascript and I want to associate an image to each item dynamically as well, but I have not found any solutions:

HTML snippet

<label for="activity">Choose an Activity:</label>
<select id="activity" name="activity">
</select>
    
<div id="hide1" style="display:none;">Shown when hovers over the first value in dropdown</div>
<div id="hide2" style="display:none;">Shown when hovers over the second value in dropdown</div>
<div id="hide3" style="display:none;">Shown when hovers over the third value in dropdown</div>

Javascript - The following function is responsible for creating the option element and id for items in dropdown. I am calling this function to dynamically create items for dropdown list.

  function createActivityDropdown (){
    activities = Object.keys(data);
    let sel = document.getElementById("activity");

    for(let key=0;key<activities.length;key++){
      let opt = document.createElement("option");
      let idNum = key.toString();
      
      opt.className = "option".concat(idNum)
      opt.value = activities[key];
      opt.innerHTML = activities[key];
      sel.appendChild(opt)
    }
    activity = sel.value;
  }

You could create an activities.src field in your data object so you can pass the image path. Then on your loop you could create an image element and apend it to the option element. Try something like that:

function createActivityDropdown (){
activities = Object.keys(data);
let sel = document.getElementById("activity");

for(let key=0;key<activities.length;key++){
  let opt = document.createElement("option");
  let image = document.createElement("img");
  let idNum = key.toString();
  
  opt.className = "option".concat(idNum)
  opt.value = activities[key];
  opt.innerHTML = activities[key];

  image.src = activities.src;
  image.alt = activities.alt;
  image.classList.add("option-image");

  sel.appendChild(opt);
  opt.appendChild(image);
 }
 activity = sel.value;
}

Then I would use CSS to show the image on :hover.

EDIT: If you add a class name to the image and set it to display:none and then on hover you set it to display: block it should work. CSS would be something like this:

.option-image {
    display: none;
}

.option-image:hover {
    display: block;
}

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