簡體   English   中英

單擊時如何更改div寬度?

[英]How to change div width when clicked?

我試圖做到這一點,以便當我單擊 div 時,它要么擴展整個視口寬度,要么返回到其原始寬度。 但它不起作用。 我試過 box.style.width 但沒有改變所以我用谷歌搜索並得到了 getComputedStyle()。 所以我很想控制台記錄寬度,但后來我在寬度上使用了 setProperty,但它仍然沒有用。

 const box = document.querySelector(".box"); const bsl = window.getComputedStyle(box); let i = 0; window.onload = () => { console.log(bsl.getPropertyValue("width"), i, 77); } box.onclick = () => { if (i % 2 === 0) { bsl.setProperty("width", "100vw"); } else { bsl.setProperty("width", "100px"); } i++; console.log(box.clientWidth, i); }
 * { margin: 0; padding: 0; } body { width: 100vw; height: 100vh; }.box { width: 100px; height: 100px; border-radius: 50%; background-color: rebeccapurple; animation: exc 1s linear forwards paused; } @keyframes exc { from { width: 100px; } to { width: 100vw; border-radius: 0%; } }
 <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div id="boxid" class="box"></div> </body>

顯然你的動畫有問題,特別是“暫停”檢查這個

 const box = document.querySelector(".box"); let isExpand = false; box.onclick = () => { if (isExpand) { box.style.width = "100px" box.style.borderRadius = "50%" isExpand = false } else { box.style.width = "100vw" box.style.borderRadius = "0%" isExpand = true } }
 * { margin: 0; padding: 0; } body { width: 100vw; height: 100vh; } .box { width: 100px; height: 100px; border-radius: 50%; background-color: rebeccapurple; transition: width 1s linear, border-radius 1s linear; }
 <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div id="boxid" class="box"></div> </body>

 const box = document.querySelector(".box"); let i = 0; box.onclick = () => { if (i % 2 === 0) { box.classList.add("expand") box.classList.remove("compress"); } else { box.classList.add("compress") box.classList.remove("expand"); } i++; }
 * { margin: 0; padding: 0; } body { width: 100vw; height: 100vh; } .box { width: 100px; height: 100px; border-radius: 50%; background-color: rebeccapurple; } .expand{ animation: expand 2s linear forwards paused; } .compress{ animation: compress 2s linear forwards paused; } @keyframes compress { from { width: 100vw; border-radius: 0%; } to { width: 100px; border-radius: 50%; } } @keyframes expand { from { width: 100px; } to { width: 100vw; border-radius: 0%; } }
 <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div id="boxid" class="box"></div> </body>

@scr2em 說的是對的。 現在,如果您想將 css 用於動畫,您可以添加和刪除適當的類。 我附上了相同的代碼。

暫無
暫無

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

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