我有一个块元素,根据它的状态改变它的宽度。
Here's a fiddle告诉你我的意思。
单击黑色按钮时,您将看到文本在该按钮内发生变化,从而减小了整体宽度。我想知道是否有通过CSS或JS的方式,我可以在单击按钮时获得平滑动画的宽度。
HTML
<a id="contact-button" href="#">Get in touch</a>
<div id="primary"></div>
<div id="contact-keebs"></div>
CSS
#contact-button {
background: #000;
background-size: 24px;
color: #fff;
text-decoration: none;
text-transform: uppercase;
font-weight: bold;
padding: 10px 20px;
position: absolute;
right: 0;
top: 0;
z-index: 1;
}
#primary {
background: red;
height: 200px;
position: absolute;
width: 200px;
}
#contact-keebs {
background: blue;
display: none;
height: 200px;
position: absolute;
width: 200px;
}
JS
var c = 0;
$('#contact-button').click(function (e) {
e.preventDefault();
if (c++ % 2 == 0) {
$(this).addClass('work-button').text('Work');
$('body').addClass('contact-content');
$('#contact-keebs').finish().stop().fadeIn(500);
} else {
$(this).removeClass('work-button').text('Get in touch');
$('body').removeClass('contact-content');
$('#contact-keebs').finish().stop().fadeOut(500);
}
});
答案 0 :(得分:1)
您可以使用transition
为width
设置动画。
var c = 0;
$('#contact-button').click(function(e) {
e.preventDefault();
if (c++ % 2 == 0) {
$(this).addClass('work-button').text('Work');
$('body').addClass('contact-content');
$('#contact-button').css('width', '30px');
$('#contact-keebs').finish().stop().fadeIn(500);
} else {
$(this).removeClass('work-button').text('Get in touch');
$('#contact-button').css('width', '85px');
$('body').removeClass('contact-content');
$('#contact-keebs').finish().stop().fadeOut(500);
}
});
&#13;
#contact-button {
background: #000;
background-size: 24px;
color: #fff;
width: 85px;
text-decoration: none;
text-transform: uppercase;
font-weight: bold;
padding: 10px 20px;
position: absolute;
right: 0;
top: 0;
z-index: 1;
transition: all 0.4s cubic-bezier(.09,1.31,1,1.28);
white-space: pre;
overflow: hidden;
}
#primary {
background: red;
height: 200px;
position: absolute;
width: 200px;
}
#contact-keebs {
background: blue;
display: none;
height: 200px;
position: absolute;
width: 200px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="contact-button" href="#">Get in touch</a>
<div id="primary"></div>
<div id="contact-keebs"></div>
&#13;
答案 1 :(得分:0)
在#contact-button
上使用此CSS过渡:宽度2s线性;
答案 2 :(得分:0)
也许不是最好的解决方案,但你可以使用CSS过渡并指定宽度(这是不好的部分)。这样的事情:http://jsfiddle.net/ddac5391/12/
这个代码非常简单,在CSS中你只需将它添加到#contact-button
样式中:
overflow:hidden;
width:150px;
height:18px;
transition: width 0.5s linear;
-webkit-transition:width 0.5s linear;
(其中一些内容如height
或overflow
并非真正需要)
然后在JS中,在更改文本内容之前/之后指定框的width
:
$(this).addClass('work-button').text('Work').css({width:"70px"})
...
$(this).removeClass('work-button').text('Get in touch').css({width:"140px"});
然后点击按钮,看它增长/缩小。