首页 > 解决方案 > 将鼠标悬停在其他导航栏项目上时禁用焦点

问题描述

我遇到了一个问题,即我的导航栏项目在悬停时会出现下划线动画。单击后,动画将保留在那里。但是,如果我将鼠标悬停在相邻的导航栏项目上,两条线将彼此相邻出现,看起来像一条长线。在此处输入图像描述

所以这里 produkt 是专注的,而 preise 是悬停的。我希望,当我将鼠标悬停在 preise 上时,产品会变得不集中。但是,如果我不选择 preise,则将焦点“返回”到产品上。下面的代码

.undeline:before {
    content: '';
    position: absolute;
    width: 100%;
    height: 3px;
    bottom: 0;
    left: 0;
    background: #52ae49;
    border-radius:3px;
    margin-top: -10px;
    visibility: hidden;
    transform: scaleX(0);
    transition: all 0.3s ease-in-out 0s;
}


.undeline:hover:before {
    visibility: visible;
    display: block;
    transform: scaleX(1);
}

.undeline:focus:before  {
    content: '';
    position: absolute;
    width: 100%;
    height: 3px;
    bottom: 0;
    left: 0;
    background: #52ae49;
    border-radius:3px;
    margin-top: -10px;
    visibility: visible;
    display: block;
    transform: scaleX(1);
}

我想,我将不得不使用 JavaScript 来管理它并使用 .forEach。我试过这个

    function mouseOver() {
    $(".underline").each(function() {
    $(this).blur('focus');
    });
}

function mouseOut() {
    $("underline").each(function() {
    $(this).addClass('focus');
    });
    }

但没有成功。

标签: javascriptjquerycssnavbar

解决方案


在这里,当您的意思是焦点时,我想您是在单击链接时谈论的。由于焦点更适合输入字段等html元素。

请运行下面的代码片段以查看它的实际效果。

$('.nav li').on('click', function() {
  var $link = $(this);
  if (!$link.hasClass('selected')) {
    $link.addClass('selected');
    $link.siblings().removeClass('selected');
    $link.siblings().removeClass('dimmed');
  }
});

$('.nav li').hover(
  // hover in handler
  function() {
    $(this).siblings('.selected').each(function() {
     if (!$(this).hasClass('dimmed')) {
      $(this).addClass('dimmed');
     }
    });
  },
  // hover out handler
  function() {
    $(this).siblings('.selected').each(function() {
     $(this).removeClass('dimmed');
    });
  });
.nav {
  display: flex;
}

.nav li {
  position: relative;
  list-style: none;
  padding: 5px 10px;
  text-transform: uppercase;
  cursor: pointer;
}

li.selected.dimmed:before,
li:before {
  content: '';
  position: absolute;
  width: 100%;
  height: 3px;
  bottom: 0;
  left: 0;
  background: #52ae49;
  border-radius: 3px;
  margin-top: -10px;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}

li:hover:before {
  visibility: visible;
  display: block;
  transform: scaleX(1);
}

li.selected:before {
  content: '';
  position: absolute;
  width: 100%;
  height: 3px;
  bottom: 0;
  left: 0;
  background: #52ae49;
  border-radius: 3px;
  margin-top: -10px;
  visibility: visible;
  display: block;
  transform: scaleX(1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nav">
  <li>produkt</li>
  <li>preise</li>
</div>


推荐阅读