Есть ли лучший способ сделать этот код JQuery? - PullRequest
0 голосов
/ 10 апреля 2019

В настоящее время я создаю панель навигации для мобильных устройств, которая будет расширяться при нажатии кнопки.Это расширяет определенное количество пикселей для содержимого.Когда появляется кнопка «Закрыть», она должна закрыться до первоначального размера кнопки.Размеры увеличиваются, но не уменьшаются.Вот базовая версия моего кода.

Я пытался создать переменные и множество других вещей, которые, честно говоря, не могу вспомнить, что именно я сделал.

Мой HTML:

<div class="navbar-background">
    </div>
    <div class="mobile-navbar-button">
      <div class="bar-1">
      </div>
      <div class="bar-2">
      </div>
      <p class="closebtn">&times;</p>
    </div>

Мой CSS:

.mobile-navbar-button {
  background-color: blue;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  position: fixed;
  left: 2vw;
  top: 30px;
  transition: 0.5s;
  z-index: 0;
}

.navbar-background {
  background-color: rgba(0, 0, 0, 0.9);
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
}

.closebtn {
  color: white;
  font-size: 100px;
  position: fixed;
  top: -80px;
  left: 35px;
  display: none;
  transition: 0.8s;
}
.bar-1 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 65px;
  left: 37px;
}
.bar-2 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 85px;
  left: 37px;
}

Мой jQuery:

$(document).ready(function() {
  $(".mobile-navbar-button").on('touchstart', function() {
    $('.mobile-navbar-button').css('width', '1425px');
    $('.mobile-navbar-button').css('height', '1200px');
    $('.mobile-navbar-button').css('left', '-400px');
    $('.mobile-navbar-button').css('top', '-400px');
    $('.mobile-navbar-button').find('.bar-1').css('display', 'none');
    $('.mobile-navbar-button').find('.bar-2').css('display', 'none');
    $('.closebtn').css('display', 'block');
  });
  $(".closebtn").on('touchstart', function() {
    $('.mobile-navbar-button').css('width', '90px');
    $('.mobile-navbar-button').css('height', '90px');
    $('.mobile-navbar-button').css('left', '2vw');
    $('.mobile-navbar-button').css('top', '30px');
    $('.mobile-navbar-button').find('.bar-1').css('display', 'block');
    $('.mobile-navbar-button').find('.bar-2').css('display', 'block');
  });
});

Я бы хотел, чтобы ширина и высота кнопки .mobile-navbar отразилась обратно до 90px дляширина и высота.Но в настоящее время этого не происходит.Ширина и высота как бы «прилипают» к ширине 1425 пикселей и высоте 1200 пикселей и не вернутся к тому, что я настроил в функции .closebtn.

Ответы [ 4 ]

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

Вот код несколько проще:

$(document).ready(function() {
  $(".mobile-navbar-button").on('click touchstart', function() {
    $('.mobile-navbar-button').css({
      "width": 1425 + "px",
      "height": 1200 + "px",
      "left": -400 + "px",
      "top": -400 + "px",
    });

    $('.mobile-navbar-button').find('.bar-1, .bar-2').css('display', 'none');

    $('.closebtn').css('display', 'block');
  });

  $(".closebtn").on('click touchstart', function() {
    $('.mobile-navbar-button').css({
      "width": 90 + "px",
      "height": 90 + "px",
      "left": 2 + "vw",
      "top": 30 + "px",
    });

    $('.mobile-navbar-button').find('.bar-1, .bar-2').css('display', 'block');
    $('.closebtn').css('display', 'none');
  });
});
.mobile-navbar-button {
  background-color: blue;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  position: fixed;
  left: 2vw;
  top: 30px;
  transition: 0.5s;
  z-index: 0;
  cursor: pointer;
}

.navbar-background {
  background-color: rgba(0, 0, 0, 0.9);
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
}

.closebtn {
  color: white;
  font-size: 100px;
  position: fixed;
  top: -80px;
  left: 35px;
  display: none;
  transition: 0.8s;
  cursor: pointer;
}

.bar-1 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 65px;
  left: 37px;
}

.bar-2 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 85px;
  left: 37px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="navbar-background"></div>
<div class="mobile-navbar-button">
  <div class="bar-1">
  </div>
  <div class="bar-2">
  </div>
</div>
<p class="closebtn">&times;</p>

closebtn должен был быть извлечен из элемента .mobile-navbar-button , чтобы он работал правильно, а также функция click / touchstart имела будет изменено (CSS отображение скрыто добавлено в качестве последней строки).

Он работает с событиями click и touchstart и использует синтаксис object для jQuery CSS.

Обычно хорошей идеей является отделить единицу от числа в jQuery CSS, потому что таким образом его можно использовать как число вместо строки ( 1425 - это int, но 1425px - это строка ).

0 голосов
/ 10 апреля 2019

Почему никто не задумывался о добавлении и удалении класса для кнопки навигации, чтобы сигнализировать о состоянии! манипулирование свойствами стиля из JS / jQuery ужасно, если вы решите изменить применяемый стиль. Просто используйте несколько дополнительных правил CSS и переключите класс на панели навигации. Гораздо проще и гораздо проще в обслуживании

Просто переключите класс open на панели навигации, дополнительный CSS будет обрабатывать отображение.

Я добавил обработчики событий click, чтобы немного упростить использование на устройствах без сенсорного экрана;)

$(document).ready(function() {
  var navButton = $(".mobile-navbar-button");
  var closeButton = $(".closebtn");

  navButton.on('click', function() {
          navButton.toggleClass('open')
      });

  closeButton.on('touchstart', function() {
          navButton.toggleClass('open');
      });

});
.mobile-navbar-button {
  background-color: blue;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  position: fixed;
  left: 2vw;
  top: 30px;
  transition: 0.5s;
  z-index: 0;
}

.navbar-background {
  background-color: rgba(0, 0, 0, 0.9);
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
}

.closebtn {
  color: white;
  font-size: 100px;
  position: fixed;
  top: -80px;
  left: 35px;
  display: none;
  transition: 0.8s;
}

.bar-1 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 65px;
  left: 37px;
}

.bar-2 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 85px;
  left: 37px;
}

/* Change display when 'open' class is active on .mobile-navbar-button */
.mobile-navbar-button.open {
  height: 1200px;
  left: -400px;
  top: -400px;
}

.mobile-navbar-button.open .bar-1,
.mobile-navbar-button.open .bar-2 {
  display: none;
}

.mobile-navbar-button.open .closebtn {
  display: block;
  top: 30px;
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mobile-navbar-button">
  <div class="bar-1">
  </div>
  <div class="bar-2">
  </div>
  <p class="closebtn">&times;</p>
</div>

РЕДАКТИРОВАТЬ удалены обработчики событий «touchstart»

0 голосов
/ 10 апреля 2019

Я получил его на работу, ребята!Немного дополнительной работы с кодом, которая не может быть на 100% практичной, но работает так, как я хочу!Спасибо всем за участие!Если вы хотите увидеть, что я сделал, я опубликую его в этом ответе.

Мой HTML:

<div class="navbar-fullscreen-background">
    </div>
    <div class="mobile-navbar-button">
      <div class="bar-1">
      </div>
      <div class="bar-2">
      </div>
    </div>
    <div class="navbar-background">
      <p class="closebtn">&times;</p>
    </div>

Я добавил класс navbar-background позади mobile-navbar-button, чтобычто пользователь не сможет его увидеть.

Мой CSS:

.mobile-navbar-button {
  background-color: blue;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  position: fixed;
  left: 2vw;
  top: 30px;
  transition: 0.5s;
  z-index: 3;
}

.navbar-background {
  background-color: blue;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  position: fixed;
  left: 2vw;
  top: 30px;
  transition: 0.5s;
  z-index: 2;
}

.navbar-fullscreen-background {
  background-color: rgba(0, 0, 0, 0.9);
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1;
  transition: 0.5s;
  display: none;
}

.closebtn {
  color: white;
  font-size: 100px;
  position: fixed;
  top: -80px;
  left: 35px;
  display: none;
  transition: 0.8s;
}

.bar-1 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 65px;
  left: 37px;
}
.bar-2 {
  background-color: white;
  width: 54px;
  height: 3px;
  position: fixed;
  top: 85px;
  left: 37px;
}

Затем я добавил navbar-background в CSS, а затем дал кнопку mobile-navbar, navbar-fullscreen-background и navbar-background z-index, чтобы изменить их укладку.

Мой jQuery:

$(document).ready(function() {
  $(".mobile-navbar-button").on('touchstart', function() {
    $('.navbar-background').css({'width': 1450 + 'px', 'height': 1200 + 'px', 'left': -400 + 'px', 'top': -400 + 'px',});
      $('.navbar-fullscreen-background').css('display', 'block');
        $('.mobile-navbar-button, .bar-1, .bar-2').css('display', 'none');
          $('.closebtn').css('display', 'block');
  });
  $(".closebtn").on('touchstart', function() {
    $('.navbar-background').css({'width': 90 + 'px', 'height': 90 + 'px', 'left': 2 + 'vw', 'top': 30 + 'px',});
      $('.mobile-navbar-button, .bar-1, .bar-2').css('display', 'block');
        $('.navbar-fullscreen-background').css('display', 'none');
          $('.closebtn').css('display', 'none');
  });
});

Я, наконец, взял свой jQuery (исправленную версию) и исправил его, чтобы он соответствовал моим изменениям в HTML и CSS, и смог сделать .mobile-navbar-Кнопки .bar-1 и bar-2 не отображают ничего, поэтому вместо них будет использоваться фон панели навигации в качестве области увеличения и сжатия содержимого.

Не на 100% уверен, что это лучший способ, но этотак, что сработало для меня!

0 голосов
/ 10 апреля 2019

Вот решение!

$(document).ready(function () {

    // Proper way of using multile CSS
    $('#div').css({
        'width': '500px',
        'height': '500px',
        'background': '#eee',
        'border-top-left-radius': '40px',
        'display': 'none'
    });


    $('#close').css({
        'display': 'none'
    });


    $('#open').click(function () {
        $('#div').css({
            'display': 'block'
        });
        $('#close').css({
            'display': 'block'
        });
        $(this).css({
            'display': 'none'
        });
    });


    $('#close').click(function () {
        $('#div').css({
            'display': 'none'
        });
        $('#open').css({
            'display': 'block'
        });
        $(this).css({
            'display': 'none'
        });
    });
});
button {
    background-color: blue;
    width: 90px;
    height: 90px;
    border-radius: 50%;
    position: fixed;
    left: 2vw;
    top: 5px;
    transition: all 1s ease;
    z-index: 0;
    cursor: pointer;
    color: #fff;
    font-size: 30px;
    border: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
</head>
<body>
  <button id="open"><i class="fas fa-bars"></i></button>
  <button id="close"><i class="fas fa-times"></i></button>
  <div id="div"></div>
</body>
</html>

Я также показал правильный способ использования нескольких CSS.Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...