将鼠标悬停在非有序列表中的第一个列表项上时显示文本

时间:2016-03-18 22:56:12

标签: javascript jquery html css

如果我在页面中有一个li和一些隐藏文本,当用户将鼠标悬停在ul中的第一个li时,如何显示该文本?

我不在乎这是在CSS还是JS中,只有当鼠标悬停在列表中的第一个itel而不是其他人时才会出现文本。因此,当我将鼠标悬停在咖啡上时,隐藏文字"是可见的



<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

<label style="display: none">hidden text</label>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

使用普通javascript解决方案:

<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

<label style="display: none">hidden text</label>
//logger.js
require('colors');
var _ = require('lodash');
var config = require('../config/config');

// create a noop (no operation) function for when loggin is disabled
var noop = function () {
};
// check if loggin is enabled in the config
// if it is, then use console.log
// if not then noop
var consoleLog = config.logging ? console.log.bind(console) : noop;

var logger = {
  log: function () {
    var tag = '[ ✨ LOG ✨ ]'.green;
    // arguments is an array like object with all the passed
    // in arguments to this function
    var args = _.toArray(arguments)
        .map(function (arg) {
          if (typeof arg === 'object') {
            // turn the object to a string so we
            // can log all the properties and color it
            var string = JSON.stringify(arg, null, 2);
            return tag + '  ' + string.cyan;
          } else {
            return tag + '  ' + arg.cyan;
          }
        });

    // call either console.log or noop here
    // with the console object as the context
    // and the new colored args :)
    consoleLog.apply(console, args);
  },

  error: function () {
    var args = _.toArray(arguments)
        .map(function (arg) {
          arg = arg.stack || arg;
          var name = arg.name || '[ ❌ ERROR ❌ ]';
          var log = name.yellow + '  ' + arg.red;
          return log;
        });

    consoleLog.apply(console, args);
  }
};

module.exports = logger;

答案 1 :(得分:0)

您可以使用:first选择器或first()过滤器来定位元素集合中的第一个元素。

$('ul li:first').hover(function()
{
  $('label').show();
}, function()
{
$('label').hide();
});

示例:https://jsfiddle.net/g6Lo4835/

$('ul li').first().hover(function()
{
  $('label').show();
},function()
{
  $('label').hide();
});

示例:https://jsfiddle.net/g6Lo4835/1/

答案 2 :(得分:0)

$(document).ready(function(){
  var $ul_menu = $('ul');

  $ul_menu.on('mouseover', function(e){
    if(e.target && e.target.nodeName === 'LI'){
      if($(e.target).index() === 0){
        $('label').css('display', 'initial');
      }
    }
  });
});

JSFiddle Here

我只是简单地向ul元素添加了一个事件监听器,并检查了li元素的索引,如果它是0,那么它将更新css并显示隐藏文本。

<强>已更新

  $ul_menu.on('mouseout', function(e){
     if(e.target && e.target.nodeName === 'LI'){
        if($(e.target).index() === 0){
        $label.css('display', 'none');
      }
    }
  });

您可以添加此项以在mouseout上将显示更新为none,并且只有在它是第一个li元素时才会修改它。

相关问题