2017-01-02 1 views
1

jQuery 1.12를 사용하고 있습니다. 나는 누군가가요소에 호버 클래스를 적용하려면 어떻게해야합니까?

.select-options li:hover { 
    color: gray; 
    background: #fff; 
} 

어떻게 내가 LI 요소에이 클래스를 적용 트리거하기 위해 jQuery를 사용합니까 LI 요소를 가리킬 때이 클래스가? 나는 이것을 시도했다

$(".select").bind('keydown', function(event) { 
    elt = $(this).find('.select-options li:hover') 
    if (elt.length == 0) { 
     elt = $(this).find('.select-options li:first') 
    }  // if 
    var next; 
    switch(event.keyCode){ 
    // case up 
    case 38:   
     break; 
    case 40: 
     next = $(elt).next(); 
     console.log($(next).text()); 
      $(next).trigger('mouseenter'); 
     break; 
    }  
}); 

그러나 $ (다음) .trigger ('mouseenter'); 작동하지 않는 것 같습니다. 내 피들을 여기서 확인할 수 있습니다 - http://jsfiddle.net/cwzjL2uw/15/. "상태 선택"드롭 다운을 클릭하고 위의 코드 블록을 트리거하려면 키보드의 아래쪽 키를 클릭하십시오. MDN

+0

가능한 복제 (http://stackoverflow.com/questions/4347116/trigger-css-hover-with-js)이 대 –

답변

0

:

CSS 의사 클래스는 요소의 특별한 상태를 선택할 수 지정 선택기에 추가 키워드입니다.

따라서 반드시 요소에 적용되는 클래스 일 필요는 없으며 가리키는 장치 상호 작용 (예 : 마우스)의 컨텍스트에서 호버가 사용됩니다.

귀하의 경우에는이 당신에게 출발점 제공한다 : JQuery와의 hover 이벤트로 리 요소 바인딩

:)

$(".select-options li") 
.hover(
function(e) { 
    $(this).addClass("selected"); 
}, 
function(e) { 
    $(this).closest(".select-options").find("li.selected").removeClass("selected"); 
} 
); 

$(".select").bind('keydown', function(event) { 
var currentElement = $(this).find(".select-options li.selected"); 
if (currentElement.length == 0) { 
    currentElement = $(this).find(".select-options li")[0]; 
    $(currentElement).addClass("selected"); 
    return; 
}  // if 
var nextElement; 
switch(event.keyCode){ 
// case up 
case 38: 
    nextElement = $(this).find(".select-options li")[($(this).find(".select-options li").index(currentElement) - 1) % $(this).find(".select-options li").length]; 
    break; 
case 40: 
    nextElement = $(this).find(".select-options li")[($(this).find(".select-options li").index(currentElement) + 1) % $(this).find(".select-options li").length]; 
    break; 
} 
if(currentElement !== null) { 
    $(currentElement).removeClass("selected"); 
} 
if(nextElement !== null) { 
    $(nextElement).addClass("selected"); 
} 

을};

는 CSS를

.select-options li.selected { 
    color: gray; 
    background: #fff; 
} 

이 작업 바이올린입니다을 조정하는 것이 필요합니다. [JS와 트리거 CSS 호버]의

http://jsfiddle.net/sge8g5qu/

+0

감사합니다. 한 가지만 있습니다. 마우스로 메뉴를 열고 항목 위로 마우스를 가져간 다음 위아래로 움직이기 시작하면 아무 일도 일어나지 않습니다 (다른 LI는 선택되지 않음). – Dave

+0

예상되는 동작 및 사용중인 브라우저는 무엇입니까? 리눅스에서 크롬 51에 대한 작품. –

+0

필자의 원래 피들에서는 누군가가 이미 "$ (this) .find ('.- 선택 옵션 li : hover')"(이것은 잘못된 Jquery 일 수 있음)를 사용하여 요소를 가리키고 있는지 감지하려고했습니다. 그런 다음 위 또는 아래를 눌러 기존 선택을 조정합니다. $ (this) .find (".select-options li.selected")는 "Tab"키를 사용하여 메뉴에있는 경우에 작동하지만 마우스로 열어 선택한 다음 마우스는 위아래로 아무 것도하지 않습니다. – Dave

관련 문제