我想做一个切换,每当单击元素时就会切换元素的高度和宽度。
let isBig = false
if (isBig) {
main.style.width = "100px";
main.style.height = "100px";
isBig = false
} else {
main.style.width = "113px";
main.style.height = "113px";
isBig = true
}
但它并没有按预期工作。有人可以帮我吗? 谢谢你
<div class="flexbox-container" id="main" onclick="staybig()">Create Account</div>
这就是我在 html 中调用该函数的地方。是的,JS 文件的链接存在。
.flexbox-container {
transition: height 0.5s, width 0.5s;
height: 100px;
width: 100px;
display: flex;
justify-content: center;
text-align: center;
align-items: center;
background-color: #492ee4;
border-radius: 50%;
display: flex;
margin: auto;
margin-top: 200px;
}
这就是CSS
您的代码似乎没有正确更新 isBig 变量。您需要将 isBig 变量移到单击事件处理程序之外,以便它在单击之间保留其状态。这是代码的更正版本:
let isBig = false;
const main = document.getElementById('yourElementId'); // Replace 'yourElementId' with the actual ID of your element
main.addEventListener('click', function() {
if (isBig) {
main.style.width = "100px";
main.style.height = "100px";
isBig = false;
} else {
main.style.width = "113px";
main.style.height = "113px";
isBig = true;
}
});