使用 jQuery 为 width() 设置动画会在下面创建某种填充。
我有一个隐藏的元素(输入),因为父级有溢出:隐藏。当用户单击链接时,链接本身会消失并将宽度更改为输入之一,因此输入会神奇地出现。不幸的是,它只会在动画期间创建某种填充。
这是一个 jsfiddle(单击“s”框或 HTML 上的任意位置):
这是JS:
jQuery('#search').on('click', function(){
event.stopPropagation();
var formWidth = jQuery(this).children('form').width();
jQuery(this).children('form').animate({left: "0"});
jQuery(this).animate({width: formWidth});
jQuery('#search form input').focus();
});
jQuery('html').click(function(){
jQuery('#search').animate({width: "2rem"});
jQuery('#search form').animate({left: "2rem"});
jQuery('#search form input').val('');
});
和 HTML:
<div id="menu">
<a href="#" class="link">Other links</a>
<a href="#" class="link">Other links</a>
<div id="search">
<i class="icon">s</i>
<form method="get" action="">
<input type="text" placeholder="type to search..." />
</form>
</div>
</div>
<p>Click on "s" to show search input. Or anywhere on the site to hide it. Why does it add some kind of margin / padding on click?</p>
<marquee>Welcome! It's 1999 all over again!</marquee>
和 CSS:
body {
padding: 0;
margin: 0;
text-align: center;
}
#menu {
text-align: right;
background: #555;
margin: 0 auto;
width: 500px;
overflow: hidden;
}
#search {
display: inline-block;
width: 2rem;
cursor: pointer;
position: relative;
}
#search,
#search i {
line-height: 2rem;
text-align: center;
width: 2rem;
height: 2rem;
background: #eee;
}
#search form {
position: absolute;
top: -2px;
left: 2rem;
width: 180px;
}
#search form input {
position: relative;
height: 2rem;
border: 0;
width: 180px;
background: #efefef;
}
marquee {
width: 500px;
margin: 0 auto;
}
再次提琴:http: //jsfiddle.net/46XxU/1/