我正在制作一个导航栏并使其正常工作。然而我想改变我的写作。有重复的代码,如下所示:
$("nav span").mouseover(function(){
var currentColor = $("#" +$(this).attr("data-loc")).css("backgroundColor");
var currentPos = $(this).position().left;
if ($(this).attr("data-loc") === "home"){
$("#hoverstyle").animate({"left":currentPos},150);
$("#hoverstyle").css("backgroundColor",currentColor);
$("#hoverstyle").css({width:$(this).width()});
}
else if($(this).attr("data-loc") === "writer"){
$("#hoverstyle").animate({"left":currentPos},150);
$("#hoverstyle").css("backgroundColor",currentColor);
$("#hoverstyle").css({width:$(this).width()});
}
else if($(this).attr("data-loc") === "historian"){
$("#hoverstyle").animate({"left":currentPos},150);
$("#hoverstyle").css("backgroundColor",currentColor);
$("#hoverstyle").css({width:$(this).width()});
}
else if($(this).attr("data-loc") === "teacher"){
$("#hoverstyle").animate({"left":currentPos},150);
$("#hoverstyle").css("backgroundColor",currentColor);
$("#hoverstyle").css({width:$(this).width()});
}
else if($(this).attr("data-loc") === "fencing"){
$("#hoverstyle").animate({"left":currentPos},150);
$("#hoverstyle").css("backgroundColor",currentColor);
$("#hoverstyle").css({width:$(this).width()});
}
});
但是我不知道如何让它变得更好,我正在考虑让它成为一个循环,但我不知道 -.-.. 请帮忙!
最佳答案
我将创建一个有效 loc 值的数组,然后查看该元素是否在该数组中具有值。
var locs = ['home', 'writer', 'historian', 'teacher', 'fencing'];
var thisLoc = $(this).attr('data-loc');
if (locs.indexOf(thisLoc) > -1) {
//do stuff
}
Array 的 indexOf
方法返回该项目的索引(如果在数组中找到该项目)。否则返回-1
。因此,如果您超过 -1
,您就知道 data-loc
值在您的数组中,您可以采取操作。
您还可以通过重用 $('#hoverstyle')
对象来清理 jQuery 操作,这称为链接。 jQuery 的方法通常返回 jQuery 对象,以便您可以链接调用而无需再次查找该对象。您可以将 css()
调用合并到一个传入具有两个属性的对象的调用中。
$("#hoverstyle")
.animate({"left":currentPos},150)
.css({
backgroundColor: currentColor,
width:$(this).width()
});
关于Javascript,我可以将其更改为循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21033255/