简体   繁体   English

CSS:在悬停或焦点上定位一个元素,但不能同时定位

[英]CSS: Target an element on hover OR focus, but not both

I'm using typeahead.js to create a simple dropdown list.我正在使用typeahead.js创建一个简单的下拉列表。

The user should be able to use the down key to scroll through suggestions, and be able to use the mouse to select a suggestion.用户应该能够使用向下键滚动浏览建议,并能够使用鼠标选择建议。 The suggestions should be appropriately highlighted in either of these scenarios.在这两种情况中的任何一种情况下,都应适当强调这些建议。

The problem I'm having is achieving the above without highlighting both hovered states AND when scrolling using the down/up arrows.我遇到的问题是在不突出显示悬停状态和使用向下/向上箭头滚动时实现上述目标。

This can be seen clearly in the gif below.这可以在下面的 gif 中清楚地看到。

To highlight hovered states I'm using:要突出显示我正在使用的悬停状态:

.tt-suggestion:hover {
  color: #f0f0f0;
  background-color: #0097cf;
}

And to highlight elements scrolled to with down/up arrows I'm using:并突出显示使用向下/向上箭头滚动到的元素:

.tt-cursor {
  color: #f0f0f0;
  background-color: #0097cf;
}

Note: .tt-cursor is a class that is automatically appended to the suggestion div when scrolled to, and then removed when scrolled away from.注意: .tt-cursor是一个在滚动到建议 div 时自动附加到建议 div 的类,然后在滚动离开时删除。

Here's a CodePen to get a better idea of what's happening.这是一个CodePen ,可以更好地了解正在发生的事情。

I'm using a rails backend, and handling most of this with Javascript & jQuery.我正在使用 rails 后端,并使用 Javascript 和 jQuery 处理其中的大部分内容。

Edit : For clarification.编辑:为了澄清。 I want to only highlight a suggestion when hovered OR scrolled to, instead of when hovered AND scrolled to (to avoid having more than one suggestion highlighted at one time).我只想在悬停或滚动到时突出显示建议,而不是在悬停和滚动到时突出显示(以避免一次突出显示多个建议)。

I think this is what you need and just remove the hover css我认为这就是您所需要的,只需删除悬停 css

/* .tt-suggestion:hover {
    color: #f0f0f0;
    background-color: #0097cf;
} */

  $('div').on("mouseover",'.tt-suggestion',function(){

    $('.tt-selectable').removeClass('tt-cursor')
    $('.tt-selectable').css( "color", '')
    $('.tt-selectable').css( "background-color", '')
    $(this).css( "color", '#f0f0f0')
    $(this).css( "background-color", '#0097cf')
  })
  document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;


    if (e.keyCode == '40') {
      $('.tt-selectable').css( "color", '')
      $('.tt-selectable').css( "background-color", '')
    }
   if (e.keyCode == '38') {
      $('.tt-selectable').css( "color", '')
     $('.tt-selectable').css( "background-color", '')
  }
}

It's not exactly clear what effect you want to achieve, but if you want to somehow visually show that element is both selected and hovered over, you should target both those conditions like this目前还不清楚您想要达到什么效果,但是如果您想以某种方式直观地显示该元素被选中并悬停在上方,您应该同时针对这两个条件

.tt-cursor.tt-suggestion:hover {
  background-color: red;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM