簡體   English   中英

使用 javascript 添加和刪除 class 時,Css 轉換屬性不起作用

[英]Css transition property not work when add and remove class using javascript

當我們使用 jquery 添加和刪除 class 轉換工作時,但是當我嘗試對 JavaScript 進行相同的工作時,它不起作用。

請幫我弄清楚為什么會這樣?

這是我的 HTML 代碼。

<button id="contact" onclick="showContactUs()">Contact us Form</button>

<div id="contact-us">
    <p id="hide" onclick="hideContactUs()">fdfg</p>
</div>

我的 script.js

const buttonName = document.getElementById( 'contact-us' );
      
showContactUs = () => {
    buttonName.classList.remove( 'contact-us-hidden' );
}

hideContactUs = () => {
    buttonName.classList.add( 'contact-us-hidden' );
}

我的 css 代碼

#contact-us{
  height: 400px;
  width: 400px;
  background-color: rgb(55, 151, 119);
  transition: all 1s linear;
}

.contact-us-hidden{
  display: none;
}

使用簡單的函數,而不是使用箭頭函數。

 const buttonName = document.getElementById( 'contact-us' ); function showContactUs(){ buttonName.classList.remove( 'contact-us-hidden' ); } function hideContactUs(){ buttonName.classList.add( 'contact-us-hidden' ); }
 #contact-us{ height: 400px; width: 400px; background-color: rgb(55, 151, 119); transition: all 1s linear; }.contact-us-hidden{ display: none; }
 <button id="contact" onclick="showContactUs()">Contact us Form</button> <div id="contact-us"> <p id="hide" onclick="hideContactUs()">fdfg</p> </div>

我不知道您使用的是什么 animation,但您可以執行以下操作:

 const buttonName = document.getElementById('contact-us'); function showContactUs() { buttonName.classList.remove('contact-us-hidden'); } function hideContactUs() { buttonName.classList.add('contact-us-hidden'); }
 #contact-us > div { height: 400px; width: 400px; background-color: rgb(55, 151, 119); } #contact-us, .contact-us-hidden { transition: opacity 1s linear; }.contact-us-hidden { opacity: 0; overflow: hidden; } /* hide from screen with a delay */ #contact-us.contact-us-hidden > div { margin-top: -10000px; transition: margin-top 0s 0.8s; }
 <button id="contact" onclick="showContactUs()">Contact us Form</button> <div id="contact-us"> <div> <p id="hide" onclick="hideContactUs()">fdfg</p> </div> </div> <div> blah </div>

注意, contact-us里面有一個額外的div ,如果你想完全從屏幕上隱藏它需要它,否則你可以使用你原來的 html。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM