gpt4 book ai didi

javascript - 使元素更宽,然后在达到特定点时变窄

转载 作者:行者123 更新时间:2023-11-30 13:52:54 26 4
gpt4 key购买 nike

要点:现在每次点击按钮都会使 content-div 变宽 100px。起始点是 300 像素,在 600 像素时,当用户点击按钮时,宽度应该回到 300 像素

清除:我不希望宽度直接变为 600px,然后在下一次单击时又回到 300px,模式应该像 click 1. +100px,click 2. +100px,click 3 . +100px,点击 4. -300px .. 然后重新开始。

我曾尝试应用 else if 语句,但出于某种原因,每次点击时 div 元素都会变宽,但当它变得超过 600 像素时,else if 语句将不适用。

var content = document.getElementById("content");
var btn = document.getElementById("btn");
content.style.width = "300px";
btn.addEventListener("click", function() {
if (content.style.width >= "300px") {
content.style.width = content.offsetWidth + 100 + "px"; }
else if (content.style.width >= "600px") {
content.style.width = content.offsetWidth - 300 + "px"; }
});
#content {
width: 300px;
height: 100px;
background: lightblue;
display: flex;
align-items: center; justify-content: center;
transition: all 1s ease-in-out;
}
#btn {
width: 100px; height: 50px;
background: grey;
display: flex;
align-items: center; justify-content: center;
color: white;
text-decoration: none;
}
a {
color: white;
text-decoration: none;
}
<div id="content">
</div>
<div id="btn"><a href="#">Click</a></div>

最佳答案

应该这样做:

  if (content.offsetWidth < 600) {
content.style.width = content.offsetWidth + 100 + "px";
}
else {
content.style.width = content.offsetWidth - 300 + "px";
}

var content = document.getElementById("content");
var btn = document.getElementById("btn");
content.style.width = "300px";
btn.addEventListener("click", function() {
if (content.offsetWidth < 600) {
content.style.width = content.offsetWidth + 100 + "px";
}
else {
content.style.width = content.offsetWidth - 300 + "px";
}
});
#content {
width: 300px;
height: 100px;
background: lightblue;
display: flex;
align-items: center; justify-content: center;
transition: all 1s ease-in-out;
}
#btn {
width: 100px; height: 50px;
background: grey;
display: flex;
align-items: center; justify-content: center;
color: white;
text-decoration: none;
}
a {
color: white;
text-decoration: none;
}
<div id="content">
</div>
<div id="btn"><a href="#">Click</a></div>

关于javascript - 使元素更宽,然后在达到特定点时变窄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57884919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com