调整屏幕大小时无法删除悬停效果

I can't remove hover effect when I resize the screen

本文关键字:删除 悬停 屏幕 小时 调整      更新时间:2023-09-26

当屏幕较小时,我向div 添加悬停效果。当屏幕大小变大时,div 会变成搜索框,悬停效果应该会消失。问题是悬停效果仍在继续。

看这里 - jsfiddle。

.HTML:

<div id="search">
  <i class="fa fa-search" aria-hidden="true"></i>
  <input type="search" placeholder="Ara">
</div>

.CSS:

div#search {
  position: absolute;
  top: 5px;
  width: auto;
  border: 2px solid #333;
  padding: 5px;
  right: 150px;
}
div#search i {
  font-size: 25px;
  border-right: 2px solid #333;
  padding-right: 10px;
  margin-left: 10px;
}
div#search input {
  width: 200px;
  height: 40px;
  font-size: 22px;
  border: none;
  outline: none;
  background: transparent;
  margin-left: 5px;
}
@media screen and (max-width: 1280px) {
  div#search {
    right: 40px;
    width: 32px;
    padding: 13.5px;
  }
  div#search input {
    display: none;
  }
  div#search i {
    margin: 5px;
    border: none;
  }
}

j查询:

$(document).ready(function() {
  searchHover();
  $(window).resize(function() {
    searchHover();
  });
});
function searchHover() {
  var width = $(window).width() + 17;
  if (width < 1280) {
    $('div#search').on('mouseover', function() {
      $(this).css({
        'background-color': '#00aeef',
        'transition': '0.5s',
        'border-color': '#00aeef',
        'color': 'white',
        'border-radius': '5px'
      });
    });
    $('div#search').on('mouseout', function() {
      $(this).css({
        'background-color': 'transparent',
        'transition': '0.5s',
        'border-color': '#333',
        'color': '#333',
        'border-radius': '0px'
      });
    });
  }
}

如果我正确理解了你的问题,那么我想我解决了它。看到小提琴。

您的问题是您忘记了else条款:

if (width < 1280) {
  $('div#search').on('mouseover', function() {
    $(this).css({
      'background-color': '#00aeef',
      'transition': '0.5s',
      'border-color': '#00aeef',
      'color': 'white',
      'border-radius': '5px'
    });
  });
  $('div#search').on('mouseout', function() {
    $(this).css({
      'background-color': 'transparent',
      'transition': '0.5s',
      'border-color': '#333',
      'color': '#333',
      'border-radius': '0px'
    });
  });
} else {
  $('div#search').off('mouseover mouseout');
}

如果没有 else 子句,则在宽度小于 1280 时设置事件侦听器,但在宽度大于或等于时从不关闭它们。

您可以在全屏模式下更轻松地查看它。