jQuery hover не позволяет курсору войти в раскрывающийся список

Я работаю над следующим фрагментом кода и сталкиваюсь с проблемой, когда выпадающее подменю остается внизу при наведении курсора на родительский li. Этот код должен работать как на мобильных, так и на настольных рендерах. Мобильный рендеринг работает нормально, проблема возникает только при рендеринге рабочего стола. Интересно, может ли кто-нибудь указать мне в правильном направлении.

$(document).ready(function() {
    $("#navToggle a").click(function(e){
        e.preventDefault();

        $("header > div#top-container").slideToggle("slow");
        $("header > div#bottom-container > nav").slideToggle("slow");
        $("#logo").toggleClass("menuUp menuDown");
    });

    $(window).resize(function() {
        if($( window ).width() >= "600") {
            $("header > div#top-container").show();
            $("header > div#bottom-container > nav").show();

            if($("#logo").attr('class') == "menuDown") {
                $("#logo").toggleClass("menuUp menuDown");
            }
        }
        else {
            $("header > div#top-container").hide();
            $("header > div#bottom-container > nav").hide();
        }
    });

  $("header > div#bottom-container > nav > ul > li > a").click(function(e) {
     if ($(window).width() <= "600") {
       if ($(this).siblings().size() > 0) {
         e.preventDefault();
         $(this).siblings().slideToggle("slow");
      }
    }
   });
  /////this is where the problem is occurring
  $("header > div#bottom-container > nav > ul > li > a").hover(function(e) {
     if ($(window).width() >= "600") {
       if ($(this).siblings().size() > 0) {
         e.preventDefault();
         $(this).siblings().slideToggle("slow");
      }
    }
   });

});
* {
  margin: 0;
  padding: 0;
  outline: none;
  box-sizing: border-box;
}

/* 1em @ 48em (768px) increasing to 2em @ 120em (1920px) */
@media (min-width: 48rem) {
  :root {
    font-size: calc(1rem + ((1vw - .48rem) * 1.389));
    /* .48rem = viewportWidthMinimum /100 */
    /* 1.389rem = 100 * fontSizeDifference / viewportWidthDifference */
  }
}

/* Stop font scaling above 1920px */
@media (min-width: 120em) {
  :root {
    font-size: 2rem;
  }
}

body {
  background: #eee;
  color: #444;
  -webkit-font-smoothing: antialiased;
  font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
  font-weight: 300;
  font-weight: 400;
  height: auto !important;
  height: 100%;
  min-height: 100%;
  text-rendering: optimizeLegibility;
}


header>.menuDown {
  box-shadow: 0 3px 5px rgba(0, 0, 0, .15);
}

header>.menuUp {
  box-shadow: none;
}

header>div#navToggle {
  background-color: rgba(0, 0, 0, .15);
  position: absolute;
  right: 0;
  top: 0;
  transition: all 300ms ease;
}

header>div#navToggle:hover {
  background-color: rgba(0, 0, 0, .1);
}

header>div#navToggle>a {
  color: rgba(255, 255, 255, .85);
  display: block;
  font-size: 0.85em;
  font-weight: 600;
  padding: 0 2.5rem;
  text-decoration: none;
  transition: all 300ms ease;
}

header>div#navToggle:hover>a {
  color: rgba(255, 255, 255, 1);
}

header>#top-container {
  display: none;
}

header>div#bottom-container {
  display: flex;
  flex-direction: column;
  text-align: center;
}

header>div#bottom-container>nav {
  background-color: rgb(250, 209, 14);
  display: none;
  flex: 1;
  flex-grow: 1;
  transform: all 300ms ease;
}

header>div#bottom-container nav>ul {
  list-style-type: none;
}


header>div#bottom-container nav>ul>li {
  border-bottom: 1px dotted rgba(0, 0, 0, .1);
  position: relative;
}

header>div#bottom-container nav>ul>li:last-of-type {
  border-bottom: none;
}

header>div#bottom-container nav>ul>li>a {
  display: block;
  color: rgba(0, 0, 0, .65);
  font-weight: 700;
  padding: 1.5rem 0;
  text-decoration: none;
  transition: all 250ms ease;
}

header>div#bottom-container nav>ul>li>a span.toggle {
  background-color: rgba(0, 0, 0, .05);
  border-radius: 3rem;
  color: rgba(0, 0, 0, .25);
  font-weight: 500;
  padding: 2px 8px;
  text-transform: lowercase;
}

header>div#bottom-container nav>ul>li>a span.caret {
  display: none;
}

header>div#bottom-container>nav>ul>li:hover>a {
  color: rgba(42, 35, 0, .5);
}

header>div#bottom-container>nav>ul>li>nav {
  display: none;
  overflow: hidden;
  position: absolute;
  right: 5%;
  width: 90%;
  z-index: 100;
  background-color: rgb(51, 51, 51);
}

header>nav>ul>li>nav>ul>li>a {
  color: rgba(255, 255, 255, .85);
  transition: all 300ms ease;
}

header>nav>ul>li>nav>ul>li:hover>a {
  background-color: rgba(0, 0, 0, .6);
  color: rgba(255, 255, 255, 1);
}

/* Medium screens */
@media all and (min-width: 600px) {
  header>#top-container {
    background-color: red;
    display: flex !Important;
    flex-direction: row;
    line-height: 90px;
    padding: 0 3rem;
    text-align: left;
    width: 100%;
  }

  header>#top-container>div#box {
    flex: 1;
  }

  header>#top-container>.box1 {
    background-color: green;
    flex-basis: 400px;
  }

  header>div#navToggle {
    display: none;
  }

  header>div#bottom-container {
    background-color: rgb(250, 209, 14);
    color: rgba(42, 35, 0, 1);
    flex-direction: row;
    line-height: 90px;
    padding: 0 3rem;
    position: fixed;
    text-align: left;
    width: 100%;
    border-top: .3rem solid #F9E484;
    box-shadow: 2px 5px 10px 1px rgba(0, 0, 0, 0.65);
  }

  header>div#bottom-container>nav {
    background-color: transparent;
    display: block;
  }

  header>div#bottom-container>nav>ul {
    display: flex;
    flex-flow: row wrap;
    justify-content: center;
  }

  header>div#bottom-container nav>ul>li {
    border-bottom: none;
    position: static;

  }

  header>div#bottom-container nav>ul>li>a {
    padding: 0 1.25rem;
  }

  header>div#bottom-container nav>ul>li>a span.toggle {
    display: none;
  }

  header>div#bottom-container nav>ul>li>a span.caret {
    border-bottom: 4px solid transparent;
    border-top: 4px solid rgba(42, 35, 0, 1);
    border-right: 4px solid transparent;
    border-left: 4px solid transparent;
    border-radius: 1px;
    content: "";
    display: inline-block;
    height: 0;
    margin: 0 0 0 .25rem;
    transition: 250ms all ease;
    width: 0;
    vertical-align: middle;
  }

}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>

  <header>
    <div id='top-container'>
      <div id="box" class='box1'>logo</div>
      <div id="box" class='box2'>our story</div>
      <div id="box" class='box3'>contact us</div>
      <div id="box" class='box4'>gift us a review</div>
    </div>
    <div id="navToggle"><a href="#">Menu</a></div>
    <div id='bottom-container'>
      <nav>
        <ul>
          <li><a href="#">Home</a></li>
          <li><a href="#">About</a></li>
          <li>
            <a href="#">Blog <span class="toggle">Expand</span><span class="caret"></span></a>
            <nav>
              <ul>
                <li><a href="#">Articles</a></li>
                <li><a href="#">Tutorials</a></li>
                <li><a href="#">Humour</a></li>
                <li><a href="#">Gaming</a></li>
                <li><a href="#">Music</a></li>
              </ul>
            </nav>
          </li>
          <li><a href="#">Forum</a></li>
          <li><a href="#">Help</a></li>
        </ul>
      </nav>
    </div>
  </header>


</body>
</html>


person Austin    schedule 08.01.2020    source источник
comment
Если вы присвоите окружающему li (тому, что находится вокруг пункта меню блога) класс, а затем наведете на него свое наведение, то, когда ваш курсор войдет в навигацию, вы все равно будете наводить курсор на тот же элемент... если это имеет смысл!   -  person Djave    schedule 08.01.2020
comment
Кроме того, как правило, каждый идентификатор на странице должен быть уникальным. Таким образом, этот селектор header > div#bottom-container > nav > ul > li > a может быть самой длинной записан как #bottom-container > nav > ul > li > a, а самой короткой я бы рекомендовал добавить к якорю другое имя класса, чтобы вы могли просто использовать, например, .blog-link.   -  person Djave    schedule 08.01.2020
comment
Спасибо @Djave. Я только что попытался добавить имя класса в элемент sub ‹nav› и указать это имя класса в качестве селектора в функции slideToggle. Я все еще получаю те же результаты, хотя. Как только вы покинете главную страницу, меню снова сдвинется вверх.   -  person Austin    schedule 08.01.2020


Ответы (1)


Ваш .hover находится только на вашем теге A. Когда вы наводите курсор мыши на тег A над подменю, вы фактически закрываете меню. У вас есть два варианта:

1) Поместите код наведения на LI, который содержит как меню тега A, так и подменю (NAV).

2) Наведите второй курсор на дочернее меню NAV, чтобы оно оставалось открытым. Я не рекомендую это, так как вы можете столкнуться с какой-то странной проблемой синхронизации.

Я бы также посоветовал избегать использования .hover на мобильных устройствах с условной проверкой, которая даже не прикрепляет событие, если размер документа меньше 640, поскольку это может привести к неожиданному поведению в некоторых мобильных браузерах, таких как мобильный Safari (который иногда пытается имитировать триггер события наведения, когда пользователь касается такого объекта). Мобильный Chrome этого не делает. Хотя просто совет. Кроме того, как упоминал @Djave, вы получите лучшие результаты с классом, вызывающим наведение курсора, чем поиск по тегу.

Я обновил ваш код ниже, наведя курсор на LI, а не на тег A.

$(document).ready(function() {
    $("#navToggle a").click(function(e){
        e.preventDefault();

        $("header > div#top-container").slideToggle("slow");
        $("header > div#bottom-container > nav").slideToggle("slow");
        $("#logo").toggleClass("menuUp menuDown");
    });

    $(window).resize(function() {
        if($( window ).width() >= "600") {
            $("header > div#top-container").show();
            $("header > div#bottom-container > nav").show();

            if($("#logo").attr('class') == "menuDown") {
                $("#logo").toggleClass("menuUp menuDown");
            }
        }
        else {
            $("header > div#top-container").hide();
            $("header > div#bottom-container > nav").hide();
        }
    });

  $("header > div#bottom-container > nav > ul > li > a").click(function(e) {
     if ($(window).width() <= "600") {
       if ($(this).siblings().size() > 0) {
         e.preventDefault();
         $(this).siblings().slideToggle("slow");
      }
    }
   });
  /////this is where the problem is occurring
  $("header > div#bottom-container > nav > ul > li").hover(function(e) {
     if ($(window).width() >= "600") {
       if ($(this).children("nav").size() > 0) {
         e.preventDefault();
         $(this).children("nav").slideToggle("slow");
      }
    }
   });

});
* {
  margin: 0;
  padding: 0;
  outline: none;
  box-sizing: border-box;
}

/* 1em @ 48em (768px) increasing to 2em @ 120em (1920px) */
@media (min-width: 48rem) {
  :root {
    font-size: calc(1rem + ((1vw - .48rem) * 1.389));
    /* .48rem = viewportWidthMinimum /100 */
    /* 1.389rem = 100 * fontSizeDifference / viewportWidthDifference */
  }
}

/* Stop font scaling above 1920px */
@media (min-width: 120em) {
  :root {
    font-size: 2rem;
  }
}

body {
  background: #eee;
  color: #444;
  -webkit-font-smoothing: antialiased;
  font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
  font-weight: 300;
  font-weight: 400;
  height: auto !important;
  height: 100%;
  min-height: 100%;
  text-rendering: optimizeLegibility;
}


header>.menuDown {
  box-shadow: 0 3px 5px rgba(0, 0, 0, .15);
}

header>.menuUp {
  box-shadow: none;
}

header>div#navToggle {
  background-color: rgba(0, 0, 0, .15);
  position: absolute;
  right: 0;
  top: 0;
  transition: all 300ms ease;
}

header>div#navToggle:hover {
  background-color: rgba(0, 0, 0, .1);
}

header>div#navToggle>a {
  color: rgba(255, 255, 255, .85);
  display: block;
  font-size: 0.85em;
  font-weight: 600;
  padding: 0 2.5rem;
  text-decoration: none;
  transition: all 300ms ease;
}

header>div#navToggle:hover>a {
  color: rgba(255, 255, 255, 1);
}

header>#top-container {
  display: none;
}

header>div#bottom-container {
  display: flex;
  flex-direction: column;
  text-align: center;
}

header>div#bottom-container>nav {
  background-color: rgb(250, 209, 14);
  display: none;
  flex: 1;
  flex-grow: 1;
  transform: all 300ms ease;
}

header>div#bottom-container nav>ul {
  list-style-type: none;
}


header>div#bottom-container nav>ul>li {
  border-bottom: 1px dotted rgba(0, 0, 0, .1);
  position: relative;
}

header>div#bottom-container nav>ul>li:last-of-type {
  border-bottom: none;
}

header>div#bottom-container nav>ul>li>a {
  display: block;
  color: rgba(0, 0, 0, .65);
  font-weight: 700;
  padding: 1.5rem 0;
  text-decoration: none;
  transition: all 250ms ease;
}

header>div#bottom-container nav>ul>li>a span.toggle {
  background-color: rgba(0, 0, 0, .05);
  border-radius: 3rem;
  color: rgba(0, 0, 0, .25);
  font-weight: 500;
  padding: 2px 8px;
  text-transform: lowercase;
}

header>div#bottom-container nav>ul>li>a span.caret {
  display: none;
}

header>div#bottom-container>nav>ul>li:hover>a {
  color: rgba(42, 35, 0, .5);
}

header>div#bottom-container>nav>ul>li>nav {
  display: none;
  overflow: hidden;
  position: absolute;
  right: 5%;
  width: 90%;
  z-index: 100;
  background-color: rgb(51, 51, 51);
}

header>nav>ul>li>nav>ul>li>a {
  color: rgba(255, 255, 255, .85);
  transition: all 300ms ease;
}

header>nav>ul>li>nav>ul>li:hover>a {
  background-color: rgba(0, 0, 0, .6);
  color: rgba(255, 255, 255, 1);
}

/* Medium screens */
@media all and (min-width: 600px) {
  header>#top-container {
    background-color: red;
    display: flex !Important;
    flex-direction: row;
    line-height: 90px;
    padding: 0 3rem;
    text-align: left;
    width: 100%;
  }

  header>#top-container>div#box {
    flex: 1;
  }

  header>#top-container>.box1 {
    background-color: green;
    flex-basis: 400px;
  }

  header>div#navToggle {
    display: none;
  }

  header>div#bottom-container {
    background-color: rgb(250, 209, 14);
    color: rgba(42, 35, 0, 1);
    flex-direction: row;
    line-height: 90px;
    padding: 0 3rem;
    position: fixed;
    text-align: left;
    width: 100%;
    border-top: .3rem solid #F9E484;
    box-shadow: 2px 5px 10px 1px rgba(0, 0, 0, 0.65);
  }

  header>div#bottom-container>nav {
    background-color: transparent;
    display: block;
  }

  header>div#bottom-container>nav>ul {
    display: flex;
    flex-flow: row wrap;
    justify-content: center;
  }

  header>div#bottom-container nav>ul>li {
    border-bottom: none;
    position: static;

  }

  header>div#bottom-container nav>ul>li>a {
    padding: 0 1.25rem;
  }

  header>div#bottom-container nav>ul>li>a span.toggle {
    display: none;
  }

  header>div#bottom-container nav>ul>li>a span.caret {
    border-bottom: 4px solid transparent;
    border-top: 4px solid rgba(42, 35, 0, 1);
    border-right: 4px solid transparent;
    border-left: 4px solid transparent;
    border-radius: 1px;
    content: "";
    display: inline-block;
    height: 0;
    margin: 0 0 0 .25rem;
    transition: 250ms all ease;
    width: 0;
    vertical-align: middle;
  }

}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>

  <header>
    <div id='top-container'>
      <div id="box" class='box1'>logo</div>
      <div id="box" class='box2'>our story</div>
      <div id="box" class='box3'>contact us</div>
      <div id="box" class='box4'>gift us a review</div>
    </div>
    <div id="navToggle"><a href="#">Menu</a></div>
    <div id='bottom-container'>
      <nav>
        <ul>
          <li><a href="#">Home</a></li>
          <li><a href="#">About</a></li>
          <li>
            <a href="#">Blog <span class="toggle">Expand</span><span class="caret"></span></a>
            <nav>
              <ul>
                <li><a href="#">Articles</a></li>
                <li><a href="#">Tutorials</a></li>
                <li><a href="#">Humour</a></li>
                <li><a href="#">Gaming</a></li>
                <li><a href="#">Music</a></li>
              </ul>
            </nav>
          </li>
          <li><a href="#">Forum</a></li>
          <li><a href="#">Help</a></li>
        </ul>
      </nav>
    </div>
  </header>


</body>
</html>

person HBlackorby    schedule 08.01.2020
comment
Спасибо! то, как вы это объяснили, делает гораздо больше, так как в первую очередь почему это не сработало. Также спасибо за подсказку по мобильному телефону. У меня есть размеры экрана меньше 600 пикселей с использованием события клика и наведения. - person Austin; 08.01.2020