简体   繁体   中英

Check if select option is hovered/mouse over with Javascript

We check if a select option is checked and display/replace a certain image for each option (if checked).

Here the code so far. It works nice (off course the images in the array have to be in the same order as the corresponding options in the select box).

/* IMAGES */
var fili_Path='https:/example.com/images/';
var fili_ImgAry=new  Array('','000.jpg','002.jpg','004.jpg','006.jpg'');


function Swap_fili(obj,id){
 var i=obj.selectedIndex;
 if (i<1){ return; }
 document.getElementById('myimage').src=fili_Path+fili_ImgAry[i];
}

<select onchange="Swap_fili(this,'mydiv');">
<option value="000">Typ 000</option>
<option value="002">Typ 002</option>
<option value="004">Typ 004</option>
...
</select>

<div id="mydiv"><img id="myimg" src ="_url_"></div>

We now try to display the images iside the div already when mousover/hover the option. Having absolutly no luck (and no clue) here. All hints appreciated.

You may want to consider simulating a select box and the options. That way you can include the images into the options.

 const options = document.querySelector("ul.options"); const selected = document.querySelector("div.selected"); selected.addEventListener("click", (e) => options.classList.toggle("open") ); const optionList = [...document.querySelectorAll("ul.options li")]; optionList.map( (option) => option.addEventListener("click", function() { const value = this.getElementsByTagName("span")[0].innerHTML; selected.innerHTML = value; document.querySelector("#sel").value = value; options.classList.toggle("open"); }));
 .container { display: flex; flex-wrap: wrap; width: 25%; }.selected { border: thin solid darkgray; border-radius: 5px; background: lightgray; display: flex; align-items: center; cursor: pointer; height: 1.5em; margin-bottom: .2em; padding-left: .5em; min-width: 150px; position: relative; }.selected:after { font-family: FontAwesome; content: "\f0d7"; margin-left: 1em; position: absolute; right: .5em; }.options { display: none; margin: 0; padding: 0; }.options.open { display: inline-block; } li { display: flex; justify-content: flex-start; align-items: center; cursor: pointer; } li>img { margin-right: 1em; }
 <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <form> <input type="hidden" id="sel"> <div class="container"> <div class="selected">Select an option</div> <ul class="options"> <li class="option"><img src="http://placehold.it/50/00ff00"><span>Option 1</span></li> <li class="option"><img src="http://placehold.it/50/ff0000"><span>Option 2</span></li> <li class="option"><img src="http://placehold.it/50/0000ff"><span>Option 3</span></li> </ul> </div> </form>

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