我仍在学习 javascript,并且一直在寻找使我的代码更好的方法。我写了这个很长的if else 语句。我想知道是否有更简单的方法来实现这一点。此代码使用jquery transit为旋转设置动画。基本上,当用户单击链接时,导航会将单击的链接旋转到顶部位置。导航定位在一个圆圈中。
var rotation = 0;
$('nav ul li a').bind('click', function () {
'use strict';
var item = $(this).parent();
var itemI = item.index();
var navAll = $(this).parents('ul');
var pos0 = (rotation === 0);
var pos1 = (rotation === 90);
var pos2 = (rotation === 180);
var pos3 = (rotation === 270);
var item0 = (itemI === 0);
var item1 = (itemI === 1);
var item2 = (itemI === 2);
var item3 = (itemI === 3);
//------------------pos0 = 0----------------------------
if (pos0 && item0) {
//do nothing 0
} else if (pos0 && item1) {
navAll.transition({
rotate: '-=90deg'
});
$('nav ul li a').transition({
rotate: '90deg'
});
rotation = 270;
} else if (pos0 && item2) {
navAll.transition({
rotate: '-=180deg'
});
$('nav ul li a').transition({
rotate: '180deg'
});
rotation = 180;
} else if (pos0 && item3) {
navAll.transition({
rotate: '+=90deg'
});
$('nav ul li a').transition({
rotate: '-90deg'
});
rotation = 90;
}
//------------------pos1 = 90----------------------------
else if (pos1 && item0) {
navAll.transition({
rotate: '0deg'
});
$('nav ul li a').transition({
rotate: '0deg'
});
rotation = 0;
} else if (pos1 && item1) {
navAll.transition({
rotate: '-90deg'
});
$('nav ul li a').transition({
rotate: '90deg'
});
rotation = 270;
} else if (pos1 && item2) {
navAll.transition({
rotate: '+=90deg'
});
$('nav ul li a').transition({
rotate: '-180deg'
});
rotation = 180;
} else if (pos1 && item3) {
//do nothing 90
}
//------------------pos2 = 180----------------------------
else if (pos2 && item0) {
navAll.transition({
rotate: '0deg'
});
$('nav ul li a').transition({
rotate: '0deg'
});
rotation = 0;
} else if (pos2 && item1) {
navAll.transition({
rotate: '-90deg'
});
$('nav ul li a').transition({
rotate: '90deg'
});
rotation = 270;
} else if (pos2 && item2) {
//do nothing
rotation = 180;
} else if (pos2 && item3) {
navAll.transition({
rotate: '-=90deg'
});
$('nav ul li a').transition({
rotate: '-90deg'
});
rotation = 90;
}
//------------------pos3 = 270----------------------------
else if (pos3 && item0) {
navAll.transition({
rotate: '0deg'
});
$('nav ul li a').transition({
rotate: '0deg'
});
rotation = 0;
} else if (pos3 && item1) {
//do nothing
} else if (pos3 && item2) {
navAll.transition({
rotate: '-=90deg'
});
$('nav ul li a').transition({
rotate: '180deg'
});
rotation = 180;
} else if (pos3 && item3) {
navAll.transition({
rotate: '-=180deg'
});
$('nav ul li a').transition({
rotate: '-90deg'
});
rotation = 90;
}
});