How to simulate a hang from Javascript to keydown?

At first, I would like to use only native JavaScript to accomplish this task.

Let's say I have to create an individual drop-down list, and the HTML code looks something like this.

<div class="dropdown">
  <span class="dropdown-label" style="display:block">Select a thing</span>
  <ul class="dropdownItemContainer">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
  </ul>
</div>

In the CSS file, I have something close to this:

ul.dropdownItemContainer li:hover {
  background-color: #FF0000;
}

Yes, in fact, there is no downward behavior, but this is not the point of discussion in fact. The problem is that I could not come up with a decent way to enable keyboard controls for this drop-down list. The desired result is as follows: I press the down key, and the first parameter is highlighted; I click it again, and the second option is highlighted, etc.

, ( JS), - ul, stick'em JS- "".

, : hover, CSS . ?

+5
4

li- ​​ keydown. , , .

var active = document.querySelector(".hover") || document.querySelector(".dropdownItemContainer li");

document.addEventListener("keydown",handler);
document.addEventListener("mouseover",handler);

function handler(e){
    console.log(e.which);
        active.classList.remove("hover");
    if (e.which == 40){
        active = active.nextElementSibling || active;
    }else if (e.which == 38){      
        active = active.previousElementSibling || active;
    }else{
        active = e.target;
    }
        active.classList.add("hover");
}

<

+7

js , JavaScript Event . , hover, , onclick

JS

  document.getElementById('id').addEventListener('focus',function(e){
    //place code that want ran at event happened
  }  

JQuery , ,...

  $('#id')bind('focus',function(e){
    //place code that want ran at event happened
  }

http://www.quirksmode.org/dom/events/index.html

0

hover css. , .

Code

var dropDown = document.getElementsByClassName("dropdownItemContainer")[0]

document.addEventListener("keydown",function (e) {
    if(e.keyCode == 38 || e.keyCode == 40 ) {
        var key = e.keyCode
        var hovered = dropDown.getElementsByClassName("hovered")
        if(hovered.length != 0 ) {
            cur = hovered[0]
            cur.className = ""
            cur = cur[(key==38?"previous":"next")+"ElementSibling"] || dropDown.children[key==38?dropDown.children.length-1:0] 
        } else {
            cur = dropDown.children[key==38?dropDown.children.length-1:0]
        }
        cur.className="hovered"
    }
});


dropDown.addEventListener("mouseover",function (e) {
    for( var i = 0,j; j = dropDown.getElementsByClassName("hovered")[i];i++)
        j.className = "";
    e.srcElement.className = "hovered";
});

JSFiddle

0

All Articles