简体   繁体   English

更改窗口大小调整类

[英]Change class on window resize

I need to change className on widows resize event, but I need change class without any transition between. 我需要在寡妇调整大小事件上更改className,但我需要更改类之间没有任何过渡。

Here is my logic: 这是我的逻辑:

1) By default make div invisible. 1)默认情况下,使div不可见。

<div></div>

div {
   display: none; 
   height: 150px;
   background: #3763ff;
}

2) When one of class added - make it visible 2)当添加一个类时-使它可见

.big {
  display: block;
  width: 100%;
  transition: .3s ease-out;
}

.small {
  display: block;
  width: 250px;
  transition: .3s ease-in-out;
}

3) On resize event I check if screen width smaller then 768 - add class 'small' else add class 'big' 3)在调整大小事件中,我检查屏幕宽度是否小于768,然后添加类“小”,否则添加类“大”

var element = document.querySelector('div');

element.classList.add('big');

window.addEventListener('resize', function () {
  var currentWidth = Math.min(window.innerWidth || Infinity, screen.width),
      currentClass = currentWidth > 768 ? 'big' : 'small';

  element.classList.add('no-transition');
  element.classList.remove('big', 'small');
  element.classList.add(currentClass);
  element.classList.remove('no-transition');
});

I expected then one class will be removed, in this moment div will be invisible, and after this the second class will be added and div will become visible, without transition. 我期望然后将删除一个类,此刻div将不可见,此后将添加第二个类,并且div将变为可见,而不会过渡。

But now I have transition between class changed: 但是现在我已经在班级之间转换了: 结果

How I can avoid this ? 我如何避免这种情况?

Here is my CodePen 这是我的CodePen

change the next code: 更改下一个代码:

  element.classList.add('no-transition');
  setTimeout(() => {
    element.classList.remove('big', 'small');
    element.classList.add(currentClass);
    setTimeout(() => {
      element.classList.remove('no-transition');
    }, 0);
  }, 0);

btw on chrome I saw the transition on your example, not with this change 顺便说一句,我在您的示例中看到了过渡,而不是此更改

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

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