【问题标题】:How do I apply a hover class to my element?如何将悬停类应用于我的元素?
【发布时间】:2017-01-02 19:56:59
【问题描述】:

我使用的是 jQuery 1.12。当有人将鼠标悬停在 LI 元素上时,我有这个类

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

如何使用 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;
    }    
 });

但是 $(next).trigger('mouseenter');似乎没有工作。你可以在这里查看我的小提琴——http://jsfiddle.net/cwzjL2uw/15/。单击“选择状态”下拉菜单,然后单击键盘上的向下键以触发上面的代码块。

【问题讨论】:

标签: jquery css hover mouseenter


【解决方案1】:

MDN:

CSS 伪类是添加到选择器的关键字,用于指定 要选择的元素的特殊状态。

因此它不一定是应用于元素的类, :hover 也用于指点设备交互(例如鼠标)的上下文中。

在你的情况下,这应该给你一个起点:

将你的 li 元素绑定到 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;
}

这是一个有效的小提琴。

http://jsfiddle.net/sge8g5qu/

【讨论】:

  • 谢谢。只有一件事——当我用鼠标打开菜单时,将鼠标悬停在一个项目上方,然后开始向上和向下按,没有任何反应(没有选择不同的 LI)。
  • 预期行为是什么,您使用的是什么浏览器?在 linux 上的 chrome 51 上为我工作。
  • 在我原来的小提琴中,我试图检测是否有人已经使用“$(this).find('.select-options li:hover')”(这可能是坏 Jquery)。然后向上或向下按将调整他们现有的选择。你有 $(this).find(".select-options li.selected"),如果他们使用“Tab”键进入菜单,它会起作用,但如果他们用鼠标打开它,然后使用鼠标悬停在选择上鼠标,向上或向下按不做任何事情。
  • 永远不要让任何人告诉你你不是那个人 b/c 这个答案是天才之作!
  • 如果您觉得我的回答有用,请考虑点赞并将其标记为已接受。谢谢。
猜你喜欢
  • 1970-01-01
  • 2016-08-22
  • 2011-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多