содержимое div не скрывается при щелчке тега привязки с помощью jQuery - PullRequest
0 голосов
/ 12 апреля 2019

У меня проблемы с панелью навигации.На мобильном устройстве я хочу, чтобы содержимое панели навигации было скрыто после нажатия на элемент списка.Эта проблема возникает только при изменении размера окна от большого к маленькому;это не происходит, когда размер экрана уже мал.Поэтому вы должны нажать «развернуть фрагмент», чтобы увидеть проблему.Я думаю, что-то не так с моим кодом javaScript, но я не уверен, что это такое.Спасибо!

$(document).ready(function() {

  var menuStatus = true;
  var sections = $('section');
  var nav = $('nav');
  //smooth scroll
  $("nav,#arrow").find('a').on('click', function() {
    var el = $(this),
      id = el.attr('href');

    $('html, body').animate({
      scrollTop: $(id).offset().top
    }, 500);
  });

  //hide the mobile nav after a link is clicked
  if ($(window).width() < 900) {
    $("nav li a").on('click', function() {
      $(".menu").hide();
      $('nav input:checkbox:checked').prop('checked', false);
    });

    $("nav input").on('click', function() {
      $(".menu").show();
    });
  }

  //show desktop nav when the screen is at least 900px
  $(window).on('resize', function() {
    var win = $(this);
    if (win.width() > 900) {
      $(".menu").show();
    }
  });
});
nav {
  position: absolute;
  width: 100%;
  z-index: 10;
}

nav img {
  height: 150px;
}

nav ul {
  list-style: none;
  overflow: hidden;
}

.nav__container {
  max-width: 1100px;
  margin: 0 auto;
  padding: 10px 40px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

nav li a {
  display: block;
  padding: 20px 20px;
  text-decoration: none;
  color: #fff;
  font-size: 110%;
  text-transform: uppercase;
  font-family: 'Rajdhani', sans-serif;
  font-weight: 600;
}

nav ul li a:hover {
  color: #5f3917;
  background-color: #fbd802;
  cursor: pointer;
}

a.active {
  color: #1CAB1D;
}

nav .menu {
  clear: both;
  max-height: 0;
  -webkit-transition: max-height .2s ease-out;
  -o-transition: max-height .2s ease-out;
  transition: max-height .2s ease-out;
}

nav .menu-icon {
  margin-top: 5px;
  cursor: pointer;
  float: right;
  padding: 28px 20px;
  position: relative;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}


/*close icon*/

nav .menu-icon .navicon {
  background: #b32025;
  display: block;
  height: 2px;
  position: relative;
  -webkit-transition: background .2s ease-out;
  -o-transition: background .2s ease-out;
  transition: background .2s ease-out;
  width: 18px;
}


/*menu icon bottom and top lines*/

nav .menu-icon .navicon:before,
nav .menu-icon .navicon:after {
  background: #b32025;
  content: '';
  display: block;
  height: 100%;
  position: absolute;
  -webkit-transition: all .2s ease-out;
  -o-transition: all .2s ease-out;
  transition: all .2s ease-out;
  width: 100%;
}

nav .menu-icon .navicon:before {
  top: 5px;
}

nav .menu-icon .navicon:after {
  top: -5px;
}


/* menu btn */

nav .menu-btn {
  display: none;
}


/*height of vertical menu*/

nav .menu-btn:checked~.menu {
  max-height: 300px;
}

nav .menu-btn:checked~.menu-icon .navicon {
  background: transparent;
}


/*when clicked animate*/

nav .menu-btn:checked~.menu-icon .navicon:before {
  -webkit-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  transform: rotate(-45deg);
}


/*when clicked animate*/

nav .menu-btn:checked~.menu-icon .navicon:after {
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}

nav .menu-btn:checked~.menu-icon:not(.steps) .navicon:before,
nav .menu-btn:checked~.menu-icon:not(.steps) .navicon:after {
  top: 0;
}


/* MEDIA QUERIES */

@media only screen and (max-width: 730px) {
  nav li:not(:last-child) {
    border-right: none;
    border-bottom: 1px solid rgba(252, 65, 65, 0.2);
  }
  nav ul {
    padding: 0;
  }
  .nav__wrapper {
    display: inline;
  }
  .container {
    padding: 100px 20px;
  }
}

@media only screen and (max-width: 730px) {
  nav {
    background-color: #fbd802;
  }
  nav img {
    height: 70px;
  }
  nav li:not(:last-child) {
    border-right: none;
    border-bottom: 1px solid rgba(252, 65, 65, 0.2);
  }
  nav ul {
    padding: 0;
  }
  nav li {
    text-align: center;
  }
  .nav__container {
    display: block;
  }
}

@media only screen and (min-width: 730px) {
  ul {
    display: flex;
  }
  nav .menu {
    max-height: none;
  }
  nav .menu-icon {
    display: none;
  }
}

.container {
  max-width: 1100px;
  margin: 0 auto;
  padding: 100px 40px;
}

section {
  height: 100vh;
}

#home {
  background: red;
}

#aboutUs {
  background: blue;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<body>
  <section id="home">
    <nav>
      <div class="nav__container">
        <img id="logo" src="https://via.placeholder.com/150" alt="logo">
        <input class="menu-btn" type="checkbox" id="menu-btn" />
        <label class="menu-icon" for="menu-btn"><span class="navicon"></span></label>
        <ul class="menu">
          <li><a href="#aboutUs">about us</a></li>
          <li><a href="#menu">menu</a></li>
          <li><a href="#gallery">gallery</a></li>
          <li><a href="#contact">contact</a></li>
        </ul>
      </div>
    </nav>
  </section>

  <section id="aboutUs">

  </section>



</body>

</html>

1 Ответ

1 голос
/ 13 апреля 2019

Я обнаружил следующую ошибку при запуске вашего скрипта: Uncaught TypeError: Cannot read property 'top' of undefined.

Есть 2 способа это исправить. Либо добавьте список всех элементов в href, а не просто #aboutUs, либо измените свой JS на следующий:

$("nav,#arrow").find('a').on('click', function() {
    var elm_id = $(this).attr('href');
    var section = $(elm_id);

    if(section.length) {
        $('html, body').animate({
            scrollTop: section.offset().top
        }, 500);
    }
});

- РЕДАКТИРОВАТЬ -

Полный код:

$(document).ready(function() {
    // smooth scroll
    $("nav, #arrow").on('click', 'a', function() {
        var elm_id = $(this).attr('href');
        var section = $(elm_id);

        if(section.length) {
            $('html, body').animate({
                scrollTop: section.offset().top
            }, 500);
        }
    });

    // Handle Mobile Menu
    var $window = $(window);
    var $menu = $(".menu");
    $("nav li a").on('click', function() {
        if ($window.width() < 900) {
            $menu.hide();
            $('nav input:checkbox:checked').prop('checked', false);
        }
    });
    $("nav input").on('click', function() {
        if ($window.width() < 900) {
            $menu.show();
        }
    });
    // show desktop nav when the screen is at least 900px
    $window.on('resize', function() {
        if ($window.width() > 900) {
            $menu.show();
        } else {
            $menu.hide();
        }
    });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...