jQuery .outerHeight () для элемента возвращает неправильный размер при изменении ориентации - PullRequest
2 голосов
/ 19 июня 2020

Я пытаюсь получить externalHeight моей верхней панели навигации на моем веб-сайте для некоторых расчетов, и он отлично работает при загрузке / перезагрузке веб-страницы. Однако он возвращает неправильную высоту, когда я меняю ориентацию экрана в Chrome Developer Tools на альбомную. Мой код прослушивает событие изменения размера перед тем, как получить outerHeight, поэтому я не уверен, почему он возвращает неправильную высоту при изменении ориентации веб-страницы, но правильную высоту при загрузке / перезагрузке веб-страницы. Я думаю, это может быть связано с тем, что слушатель resize не ждет, пока страница полностью загрузится после изменения ориентации, но я не уверен.

Для фрагмента кода я попытался добавить к нему Bootstrap 4.5 но он продолжал возвращать ошибку. Если бы кто-то хотел добавить это, кто знает, как это сделать, это было бы очень полезно, чтобы страница была более точной при запуске фрагмента кода.

body {
  background-position: center center;
  background-size: auto;
  position: absolute;
  overflow-x: hidden;
  overflow-y: scroll;
  width: 100%;
  height: 100%;
  font-family: 'Montserrat', sans-serif;
  color: white;
}

a {
  color: white;
}

a:hover {
  text-decoration: none;
  color: white;
}

#content-wrapper {
  overflow-y: scroll;
  -ms-overflow-style: none;
  overflow: -moz-scrollbars-none;
}

#content-wrapper::-webkit-scrollbar {
  display: none;
}

#top_navbar {
  padding: 0;
}

.navbar-brand {
  padding: 0;
}

#navbar_logo {
  width: 15vw;
  margin-right: 6vw;
  margin-left: 0 !important;
}

.nav-link {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 2vw;
  -webkit-text-fill-color: white;
  -webkit-text-stroke-width: 1px;
  -webkit-text-stroke-color: #1b1b1b;
  letter-spacing: 1px;
}

.nav-link:hover {
  -webkit-text-fill-color: #1b1b1b;
  -webkit-text-stroke-width: 1px;
  -webkit-text-stroke-color: white;
}

.nav-item {
  margin-left: 3vw;
  margin-right: 3vw;
}

#bottom_footer,
#legal_documents {
  background-color: #1b1b1b;
  width: 100%;
  position: absolute;
  display: table;
  bottom: 0;
  text-align: center;
  padding-top: 1%;
  padding-bottom: .4%;
}

#legal_documents {
  bottom: unset;
  font-size: 10px;
  padding-bottom: .6% !important;
}

#social_buttons::selection {
  color: none;
  background: none;
}

#social_buttons::-moz-selection {
  color: none;
  background: none;
}

#social_buttons a {
  display: inline-block;
  margin: 0 15px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
}

#bottom_footer a:hover,
#legal_documents a:hover {
  opacity: 0.5;
}
image

Ответы [ 2 ]

1 голос
/ 20 июня 2020

Я разобрался в проблеме. Причина, по которой методы jQuery высоты возвращали неправильный расчет высоты при изменении ориентации экрана на альбомную, заключалась в том, что верхняя панель навигации вносила определенные изменения, и эти изменения были внесены после получения высоты верхней панели навигации. Эти изменения должны были быть внесены до получения высоты верхней панели навигации. Изменения, внесенные в верхнюю панель навигации, включают размер и фактическое изображение #navbar-logo, а также установку #content-wrapper's margin-top на 0. После замены кода и ожидания загрузки изображения правильная высота возвращалась для каждой ориентации. изменить.

  if (window_width <= 575) {
    $("#navbar_logo").attr("src", "/static/images/title-logo-mobile.jpg");
  } else {
    $("#navbar_logo").attr("src", "/static/images/title-logo.jpg");
  }

  $("#navbar_logo").on("load", function() {
    if (window_width <= 575) {
      $("#navbar_logo").css({"width":"28vw", "margin-left":"0"});
      navbar_height = $("#top_navbar").outerHeight(true) + 10;
      $('#content-wrapper').css("margin-top", navbar_height);
    } else {
      $("#navbar_logo").css({"width":"15vw", "margin-left":"3vw"});
      navbar_height = $("#top_navbar").outerHeight(true);
      $('#content-wrapper').css("margin-top", 0);
    }
    container_height = window_height - navbar_height - footer_height;
    $("#content-wrapper").css("height", container_height);
  });
1 голос
/ 20 июня 2020
  1. Добавьте <meta name="viewport" content="width=device-width, initial-scale=1"> в свой тег <head>. Это поможет просматривать ваш сайт в правильном масштабе CSS и по ширине устройства. Подробнее об этом здесь https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag

  2. Вы можете добавить специальный window.addEventListener("orientationchange", function() { ... }); слушатель. Название говорит обо всем. Подробнее об этом здесь https://developer.mozilla.org/en-US/docs/Web/API/Window/orientationchange_event

$(window).on('resize', function() {
  window_width = $(window).width() + (window.innerWidth - document.documentElement.clientWidth);
  resizeContainer(window_width);
});

window.addEventListener("orientationchange", function() {
  window_width = $(window).width() + (window.innerWidth - document.documentElement.clientWidth);
  resizeContainer(window_width);
});

function resizeContainer(window_width) {
  let container_height;
  let navbar_height;
  let window_height = $(window).height();
  let footer_height = $("#bottom_footer").innerHeight();

  if (window_width <= 575) {
    navbar_height = $("#top_navbar").outerHeight(true) + 10;
    $('#content-wrapper').css("margin-top", navbar_height);
    $("#navbar_logo").attr("src", "/static/images/title-logo-mobile.jpg");
    $("#navbar_logo").css({
      "width": "28vw",
      "margin-left": "0"
    });
  } else {
    navbar_height = $("#top_navbar").outerHeight(true);
    console.log(navbar_height);
    $('#content-wrapper').css("margin-top", 0);
    $("#navbar_logo").attr("src", "/static/images/title-logo.jpg");
    $("#navbar_logo").css({
      "width": "15vw",
      "margin-left": "3vw"
    });
  }

  container_height = window_height - navbar_height - footer_height;
  $("#content-wrapper").css("height", container_height);
}
body {
  background-position: center center;
  background-size: auto;
  position: absolute;
  overflow-x: hidden;
  overflow-y: hidden;
  width: 100%;
  height: 100%;
  font-family: 'Montserrat', sans-serif;
  color: white;
}

a {
  color: white;
}

a:hover {
  text-decoration: none;
  color: white;
}

#content-wrapper {
  overflow-y: scroll;
  -ms-overflow-style: none;
  overflow: -moz-scrollbars-none;
}

#content-wrapper::-webkit-scrollbar {
  display: none;
}

#top_navbar {
  padding: 0;
}

.navbar-brand {
  padding: 0;
}

#navbar_logo {
  width: 15vw;
  margin-right: 6vw;
  margin-left: 0 !important;
}

.nav-link {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 2vw;
  -webkit-text-fill-color: white;
  -webkit-text-stroke-width: 1px;
  -webkit-text-stroke-color: #1b1b1b;
  letter-spacing: 1px;
}

.nav-link:hover {
  -webkit-text-fill-color: #1b1b1b;
  -webkit-text-stroke-width: 1px;
  -webkit-text-stroke-color: white;
}

.nav-item {
  margin-left: 3vw;
  margin-right: 3vw;
}

#bottom_footer,
#legal_documents {
  background-color: #1b1b1b;
  width: 100%;
  position: fixed;
  display: table;
  bottom: 0;
  text-align: center;
  padding-top: 1%;
  padding-bottom: .4%;
}

#legal_documents {
  bottom: unset;
  font-size: 10px;
  padding-bottom: .6% !important;
}

#social_buttons::selection {
  color: none;
  background: none;
}

#social_buttons::-moz-selection {
  color: none;
  background: none;
}

#social_buttons a {
  display: inline-block;
  margin: 0 15px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
}

#bottom_footer a:hover,
#legal_documents a:hover {
  opacity: 0.5;
}
image
...