本文介绍了CSS过渡结合JS clickEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将 CSS 过渡与 JS 事件处理程序结合使用时遇到以下问题.我知道如何使用CSS过渡属性,例如:

Encountering the following issue when trying to combine CSS transitions with JS event handlers. I know how to use CSS transition property for example:

div {
    width: 50px;
    height: 50px;
    background: blue;
    transition: width 2s;
}

div:hover {
    width: 300px;
}
<div></div>

我也知道如何在 DOM 元素上放置点击处理程序,如下所示:

I also know how to put a click handler on an DOM element like this:

let eventDiv = document.querySelector('#clickMe');
let hiddenDiv = document.querySelector('#hiddenDiv');

eventDiv.onclick = () => {
  if(hiddenDiv.style.display === 'block') {
    hiddenDiv.style.display = 'none'
  } else{
  hiddenDiv.style.display = 'block';
    }
}
#clickMe{
  width: 100px;
  height: 50px;
  background-color: blue;
}

#hiddenDiv {
  width: 100px;
  height: 50px;
  background-color: green;
  display: none;
}
<div id="clickMe"></div>
<div id="hiddenDiv"></div>

当切换< div> 和 JS onclick事件?

How do I combine the two and get a CSS transition (<div> should not appear immediately but should slide in) when I toggle the visibility of the <div> with a JS onclick event?

推荐答案

根据我的评论,要结合js和过渡,您需要添加和删除一个类,该类会更改要过渡的属性.

As per my comment, to combine the js and transition, you need to add and remove a class that changes the property that you want to transition.

在下面的代码段中,我添加和删除了一个隐藏类,该隐藏类会更改其高度(上面带有过渡)

In the below snippet, I add and remove a class of hide, which changes the height (that has a trnasition on it)

let eventDiv = document.getElementById('clickMe');
let hiddenDiv = document.getElementById('hiddenDiv');

eventDiv.onclick = () => {
  if(hiddenDiv.classList.contains("hide")) {
    hiddenDiv.classList.remove("hide");
  } else{
    hiddenDiv.classList.add("hide");
  }
}
#clickMe{
  width: 100px;
  height: 50px;
  background-color: blue;
}

#hiddenDiv {
  width: 100px;
  height: 50px;
  background-color: green;
  overflow:hidden;
  transition: height 1s;
}

#hiddenDiv.hide {
  height: 0;
}
<div id="clickMe"></div>
<div id="hiddenDiv" class="hide"></div>

这篇关于CSS过渡结合JS clickEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 08:17