繁体   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