jQuery / JavaScript - 如何设置0.0251和0.4070之间的随机值(每个属性的不同值)

时间:2015-06-17 14:31:41

标签: javascript jquery

我想在 0.0251 0.4070 之间生成随机数。

来自以下代码:

<circle> r 值必须为每个属性动态设置为 0.0841,0.2541,0.3257,0.0998 ..

  

SVG代码

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
 <?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="660" height="320" viewBox="0 0 201 97">
  <g stroke="#000" stroke-width=".144">
    <circle class="st3" cx="191" cy="90" r=".3"/>
    <circle class="st3" cx="190" cy="90" r=".3"/>
    <circle class="st3" cx="189" cy="90" r=".3"/>
    <circle class="st3" cx="192" cy="89" r=".3"/>
    <circle class="st3" cx="191" cy="89" r=".3"/>
    <circle class="st3" cx="190" cy="89" r=".3"/>
    <circle class="st3" cx="193" cy="88" r=".3"/>
    <circle class="st3" cx="192" cy="88" r=".3"/>
    <circle class="st3" cx="178" cy="88" r=".3"/>
    <circle class="st3" cx="177" cy="88" r=".3"/>
    <circle class="st3" cx="194" cy="87" r=".3"/>
    <circle class="st3" cx="179" cy="87" r=".3"/>
    <circle class="st3" cx="178" cy="87" r=".3"/>
  </g>
</svg>
  

的jQuery

$("circle.st3").attr("r", (Math.random() * (0.0251 - 0.4070) + 0.4070).toFixed(4));

Online Demo

以上示例输出:

<g stroke="#000" stroke-width=".144">
    <circle class="st3" cx="191" cy="90" r="0.0973"></circle>
    <circle class="st3" cx="190" cy="90" r="0.0973"></circle>
    <circle class="st3" cx="189" cy="90" r="0.0973"></circle>
    <circle class="st3" cx="192" cy="89" r="0.0973"></circle>
    <circle class="st3" cx="191" cy="89" r="0.0973"></circle>
    <circle class="st3" cx="190" cy="89" r="0.0973"></circle>
    <circle class="st3" cx="193" cy="88" r="0.0973"></circle>
    <circle class="st3" cx="192" cy="88" r="0.0973"></circle>
    <circle class="st3" cx="178" cy="88" r="0.0973"></circle>
    <circle class="st3" cx="177" cy="88" r="0.0973"></circle>
    <circle class="st3" cx="194" cy="87" r="0.0973"></circle>
    <circle class="st3" cx="179" cy="87" r="0.0973"></circle>
    <circle class="st3" cx="178" cy="87" r="0.0973"></circle>
  </g>

但我的要求是为每个“ r ”属性显示不同的数字..

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

简单:

var upperLimit = 0.4070;
var lowerLimit = 0.0251;
var yourResult = lowerLimit + Math.random() * (upperLimit - lowerLimit);