看过几篇文章,但没有任何内容可以直接而简单地回答。我想点击一个按钮,它旁边的div平滑地设置宽度以使div更大,然后再次点击时返回到原始宽度。
答案 0 :(得分:2)
检查这个小提琴, https://jsfiddle.net/s29007nL/
HTML:
<div id="button">Click me</div>
<br/>
<div id="big">soon bigger</div>
CSS:
*{
font-family:Verdana;
}
#button {
background:lightgreen;
height:20px; width:100px;
border-radius:10px; text-align:center;
cursor:pointer;
}
#big{
background:purple;
height:50px; width:100px;
text-align:center; line-height:50px;
color:#fff;
}
.ready_to_big {
animation-name: big_it;
animation-duration: 1s;
}
@keyframes big_it {
from {width:100px;} to {width:400px;}
}
JS:
document.getElementById("button").addEventListener('click', bigTheDiv);
function bigTheDiv(){
document.getElementById("big").className = "ready_to_big";
setTimeout(function(){
document.getElementById("big").className = "";
},1000);
}
可以根据您最终的目标进行改进。
答案 1 :(得分:1)
要实现这一目标,您需要HTML
,CSS
,JS
。
查看此fiddle (无jQuery) 查看此fiddle (使用jQuery)
以下是片段(无jQuery)。
var status = 0;
document.getElementById('button').addEventListener('click', resize);
function resize() {
if (status == 0) {
document.getElementById('scene').className = 'grow';
status = 1;
} else {
document.getElementById('scene').className = 'normal';
status = 0;
}
}
&#13;
#scene {
position: absolute;
height: 200px;
background: red;
}
.normal {
width: 200px;
transition-duration: 3s;
}
.grow {
width: 400px;
transition-duration: 3s;
}
&#13;
<input id='button' type='button' value='Resize DIV' />
<br>
<div id='scene' class='normal'></div>
&#13;
以下是片段(使用jQuery)。
var status = 0;
$('#button').click(function() {
if (status == 0) {
$('#scene').removeClass("normal");
$('#scene').addClass("grow");
status = 1;
} else {
$('#scene').removeClass("grow");
$('#scene').addClass("normal");
status = 0;
}
});
&#13;
#scene {
position: absolute;
height: 200px;
background: red;
}
.normal {
width: 200px;
transition-duration: 3s;
}
.grow {
width: 400px;
transition-duration: 3s;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='button' type='button' value='Resize DIV' />
<br>
<div id='scene' class='normal'></div>
&#13;