Cleaner way to implement moving a div back and forth using jQuery?
I am trying to setup a simple example where a user can click a button on a page and divs are moved from one side of a parent div to another. If the button is clicked again the divs should move back to their original position.
I have successfully set this up, but the code feels a little clumsy to me. Can anyone recommend a cleaner way to do this than what I have done below:
var operator = '+=';
$('#clickme').click(function() {
$('#main div:even').animate({
left:oper开发者_如何学JAVAator + '200'
}, 2000);
if(operator == '+='){operator = '-=';}
else{operator = '+=';}
});
The if/else at the end of my click event is the part that seems odd to me. Any suggestions for prettying this up?
You can play with the fiddle here:
http://jsfiddle.net/S6UtE/3/
I would keep the +=
and change the 200 to -200 and back again:
var move = 200;
$('#clickme').click(function() {
$('#main div:even').animate({
left:"+="+move
}, 2000);
move = -move;
});
http://jsfiddle.net/S6UtE/7/
I don't know if you would consider this better or not?
var rightd = true;
$('#clickme').click(function() {
$('#main div:even').animate({
left:(rightd ? "+=" : "-=") + '200px'
}, 2000);
rightd = !rightd;
});
http://jsfiddle.net/S6UtE/6/
You could have a 2-element array containing '+=' and '-=' at spots 0 and 1, and do something like this:
var operat0rindex = 0;
$('#clickme').click(function() {
var operator = operators[operatorindex];
//operatorindex = (operatorindex + 1) % 2
//or more quickly/simply:
operatorindex = 1 - operatorindex;
$('#main div:even').animate({
left:operator + '200'
}, 2000);
});
You could use jQuery.data()
to avoid a global var. Something like this:
$('#clickme').click(function() {
var moved = $('#main div:even').data('moved');
var operator = moved ? '-=' : '+=';
$('#main div:even').data('moved', !moved);
$('#main div:even').animate({
left:operator + '200'
}, 2000);
});
There is another option that may not have been considered.
$('#clickme').click(function() {
$('#main div:even').each(function(index, element) {
var $this = $(this);
$this.animate({
left: parseFloat($this.css("left")) >= 200 ? "-=200" : "+=200"
}, 2000);
});
});
精彩评论