使用jQuery从数组中选择一个随机元素

And*_*rey -5 css jquery

我想用jquery动画函数设置背景颜色,我需要从数组中选择一个随机元素.

$(".menu li").hover(function() {
  $(this).animate({borderBottomColor:"#81C6DD"}, 200)
}, function() {
  $(this).animate({borderBottomColor:"#D8D9DC"}, 200)
});
Run Code Online (Sandbox Code Playgroud)

Mat*_*ttW 7

听起来你不想随机化数组,听起来你想每次从数组中选择一个随机元素.假设您调用了颜色数组colors,请使用:

var color = colors[Math.floor(colors.length * Math.random())];
Run Code Online (Sandbox Code Playgroud)

虽然我怀疑你为什么要那样做.随机颜色听起来像是一个非常丑陋且可能令人困惑的UI的配方.