直指要点:当我点击按钮时,我希望每次点击时,框的宽度增加100像素。有人能帮我实现这个目标吗?
当前,当单击按钮时,框的宽度变为400px,但我想在每次单击按钮时将宽度增加100px。
你可以在下面找到代码。

var content = document.getElementById("content");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
    content.style.width = "400px";
});

#content {
    width: 300px; height: 100px;
    background: lightblue;
    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>

最佳答案

你每次都要设置400px的宽度。您需要采取宽度,然后再增加100个PX到现有的宽度。
例如:

var width1 = content.offsetWidth
content.style.width= (width1+100)+"px";

请看下面的片段。
var content = document.getElementById("content");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
var width1 = content.offsetWidth
content.style.width= (width1+100)+"px";
});

#content {
width: 300px; height: 100px;
background: lightblue;
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 - 每次点击将宽度增加100px,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57870130/

10-10 00:31
查看更多