如何使下面列出的jQuery正确地动画?
var search = $('.searchField');
var searchButton = $('.searchSubmit');
search.on('focus', function() {
search.animate({
'right':'auto',
'left':'0'
}, 600);
searchButton.animate({
'right':'0',
'left':'auto'
}, 600);
});
search.on('focusout', function() {
search.animate({
'right':'0',
'left':'auto'
}, 600);
searchButton.animate({
'right':'auto',
'left':'0'
}, 600);
});理想情况下,我希望searchButton从左到右,在:focus上使用search切换位置。我使用动画试图让这两个元素“滑动”到它们的新位置,而不是让元素从一边跳到另一边。
目前,searchButton在:focus上没有向右转,search元素跳转到左侧,而不是具有“幻灯片”效果。
对于实时jsFiddle,单击此处。
发布于 2014-11-12 20:14:15
我认为使用简单的CSS转换是有意义的:
.searchField {
/* ... */
top: 0;
right: 0;
transition: all .6s ease;
&:focus {
/* ... */
right: 50px;
&+.searchSubmit {
left: 100%;
margin-left: -50px;
}
}
}同时删除</input>,输入元素是自关闭标记:<input />。
演示:http://jsfiddle.net/u97jkeq1/8/
发布于 2014-11-12 20:33:22
实际上,我相信@dfsq答案更好,最好是用CSS来做。但我想修复原始代码,并给其他使用您的问题的人选择方法。
演示: JSFiddle
JS
var search = $('.searchField');
var searchButton = $('.searchSubmit');
var searchWidth = $('.searchField').innerWidth();
var searchButtonWidth = $('.searchSubmit').innerWidth();
var searchContainer = searchWidth + searchButtonWidth;
$('#search').css({ width: searchContainer });
search.on('focus', function() {
search.animate({
'right':'auto',
'left':'-10'
}, 400);
searchButton.animate({
'right':'0',
'left':'400'
}, 400);
});
search.on('focusout', function() {
search.animate({
'right':'0',
'left':'50'
}, 400);
searchButton.animate({
'right':'auto',
'left':'0'
}, 400);
});
searchButton.mouseover(function() {
$('.searchIcon').css('opacity', '0.5');
});
searchButton.mouseout(function() {
$('.searchIcon').css('opacity', '1');
});
search.bind('keypress', function(event) {
if (event.keyCode == 13) {
searchButton.click();
};
});
searchButton.click(function() {
search.val('');
});发布于 2014-11-12 20:33:33
我使用边缘--右/左--来动画它们,而不是使用右/左定位。
我喜欢您使用的是右/左定位,但在这种情况下,使用边距更容易。如果使用右/左定位,还必须更新css。
另一种选择是使用javascript设置类并使用css转换来动画(就像您对不透明度所做的那样)。
search.on('focus', function() {
search.animate({
marginRight: "50"
}, 600);
searchButton.animate({
marginLeft: "450"
}, 600);
});
search.on('focusout', function() {
search.animate({
marginRight: "0"
}, 600);
searchButton.animate({
marginLeft: "0"
}, 600);
});更新的jsFiddle
https://stackoverflow.com/questions/26895503
复制相似问题