如何使用jquery随机化CSS属性的值? [英] How can I randomize the value of CSS attributes using jquery?

查看:114
本文介绍了如何使用jquery随机化CSS属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jquery使一个CSS选择器随机化它的一个html元素的值。我已经得到了所有的元素(循环通过列表边框左边的颜色)的随机选择器,但我想随机排列每个单独的列表元素在同一时间。

I'm trying to use jquery to make a css selector randomize one of its values on an html element. I've gotten as far as randomizing the selector for all of the elements (cycling through colors on a list border-left), however I want to randomize each individual list element at the same time.

如果这令人困惑(我很困惑它自己),但是你会理解,如果你运行下面的代码几次,看着边框的颜色变化。理想情况下,这些边框颜色会有所不同。

Apologies if that's confusing (I'm confused by it myself), but you'll understand if you run the below code a few times and watch the border color change. Ideally, those border colors would all be different.

非常感谢任何帮助。

<html>
<head>
    <title>Title</title>
    <script src="http://code.jquery.com/jquery-latest.min.js"
    type="text/javascript"></script>
    <style>
    .bars{
        border-left-style: solid; 
        border-left-width: 4px;
        padding-left: 10px;
    }

    ul{
        list-style-type: none;
    }
    </style>

</head>
<body>
        <ul>
            <li class="bars">
              <a>Marathon Men and Women</a>
            </li>   

            <li class="bars">
              <a>Marathon Men and Women</a>
            </li>   

            <li class="bars">
              <a>Marathon Men and Women</a>
            </li>   

            <li class="bars">
              <a>Marathon Men and Women</a>
            </li>   

            <li class="bars">
              <a>Marathon Men and Women</a>
            </li>   
         </ul>
</body>
<script>
    $(document).ready(function(){
      var colors = ["#CCCCCC","#333333","#990099"];                
      var rand = Math.floor(Math.random()*colors.length);           
      $('.bars').css("border-left-color", colors[rand]);
    });
</script>

http://jsfiddle.net/RMR42/

推荐答案

您可以使用jQuery.each()函数指定单个颜色: http://jsfiddle.net/qaF24 /

You can use jQuery.each() function to specify individual colors: http://jsfiddle.net/qaF24/

$(document).ready(function(){
    var colors = ["#CCCCCC","#333333","#990099"];                
    $('.bars').each(function() {
        var rand = Math.floor(Math.random()*colors.length);
        $(this).css("border-left-color", colors[rand]);
    });
});

这篇关于如何使用jquery随机化CSS属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆