简体   繁体   English

JavaScript 同时执行页面调整大小和重新加载事件

[英]JavaScript execute page resize and reload event simultaneously

I am trying to execute a window resize and page reload event simultaneously.我正在尝试同时执行窗口大小调整和页面重新加载事件。 When the screen size is less than 768 px, I am adding an attribute to an element.当屏幕尺寸小于 768 px 时,我向元素添加属性。 I also need that attribute added when the page is reload and a specific size as well, not just when its resized.我还需要在页面重新加载时添加该属性和特定大小,而不仅仅是在调整大小时。 The code I have below works, except when my screen size hs < 769 px, it takes a few seconds for the attribute to be added which affects how it looks.我下面的代码有效,除了当我的屏幕尺寸 hs < 769 px 时,添加属性需要几秒钟,这会影响它的外观。 Any tips on how I can fix this?有关如何解决此问题的任何提示?

window.onload = function(event) {

var element = document.querySelector('.filter-select');

if (window.innerWidth < 768)  {
  element.classList.add('testing');
  element.removeAttribute("size", "4")
  element.removeAttribute("multiple", "yes")    
} else {
       element.classList.remove('testing');
    }    
}


document.addEventListener("DOMContentLoaded", function(event) {
  var element = document.querySelector('.filter-select');

  function resize() {
    if (window.innerWidth < 768) {
      element.classList.add('testing');
      element.removeAttribute("size", "4")
      element.removeAttribute("multiple", "yes")
    } else {
      element.classList.remove('testing');
    }
  }
  window.onresize = resize;
});

My only guess is that you doubled up the same process under different events and these events happen at different times thus the NOTICABLE lag.. if this doesn't solve.. this is an amazing question I already upvoted..我唯一的猜测是你在不同的事件下将相同的过程加倍,并且这些事件发生在不同的时间,因此明显的滞后......如果这不能解决......这是一个我已经投票赞成的惊人问题......

function resize() {
  var element = document.querySelector('.filter-select')
  if (window.innerWidth < 768) {
    element.classList.add('testing')
    element.removeAttribute("size", "4")
    element.removeAttribute("multiple", "yes")
  }
  else {
    element.classList.remove('testing');
  }
}
window.onload=resize

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM