jquery段始终显示错误的数字?

时间:2014-11-28 13:26:56

标签: javascript jquery

我正在尝试使用jquery创建一个财富类动画的轮子,但由于某种原因,我使用的代码总是显示错误的数字!

这里是jsfiddle:http://jsfiddle.net/wf49mqaa/2/

点击滚轮中的白色区域以查看动画,您将看到错误的数字将会显示!

目前我的jquery代码中只有4列和4个段但是将来我将从数据库中提取段的数量,我需要它始终正常工作并显示正确的数字。 / p>

我尝试了将segment = Math.ceil(((percent/100) * 4)),更改为segment = Math.ceil(((percent/100) * 4) -1),以及segment = Math.ceil(((percent/100) * 5)),

的所有内容

它仍然显示错误的数字!

有人可以就此提出建议吗?

由于

1 个答案:

答案 0 :(得分:1)

我使用的代码的一部分,我在Non-working demo from sitepoint中找到了。深入挖掘有两个不同的错误/问题来解决财富轮行为:

第一:如何定义学位:

// existing code fragment (wrong)
var deg = 1500 + Math.round(Math.random() * 1500);

这会导致车轮停在一个完全随机的位置,但这不是你需要的。车轮应始终停在标记位置,它应该只是随机数段转动。

// supposing you have a wheel with 4 segments (here the items array):

var deg = 0, /* basic degree */
    spinbase = 1080, /* basic spinning of the wheel, here 3 times full turn */
    items = [1,2,3,4];

// your spinning function...
spin: function () {
    var min = 1, 
        max = 10, 
        rand = Math.floor(min + Math.random()*(max+1-min));
    [...]
        // like this you'll stop at the same position, 
        // but the wheel moved by a random number of segments
        deg = deg + ( Math.round( 360 / items.length ) * rand) + spinbase;
    [...]
}

第二:如何获得正确的细分:

简而言之:

   // where deg is the current degree, and items the array from above.
   var segmentIndex = Math.ceil(
    (deg - (360 * parseInt(deg / 360))) / 
        Math.round(360/items.length)
   );

填写算法时..

   // e.g. deg is (degree of each segment) * random (here 5) + 1080
   // deg = 1530 (1080 + ( (360/4) * 5) )
   // (1530 - (360 * parseInt( 1530 / 360))) / Math.round(360 / 4);
   // (1530 - (360 * 4)) / 90;
   // 90 / 90 = 1
   // since we have 4 segments only and the random number is higher, 
   // the wheel did another full turn + 1 (from the starting number) 
   // so we get items[ 1 ] = (result: 2);
   // due to the ceil/floor/round methods in calculation it can happen
   // that you reach the extrem values segments.length or less than 0,
   // to fix this:

    var segmentIndex = Math.ceil(
    (deg - (360 * parseInt(deg / 360))) / 
        Math.round(360/items.length)
   );

   if(target < 0 ) { target = segment.length - 1; }
   if(target === segments.length ) { target = 0; }
   alert( 'Winning: ' + items[target] );

将这些放在一起你就能得到一个有效的fortune-wheel。我允许自己创建一个幸运轮的新变种,它能够处理不同数量的段,以便更容易证明算法。