css translate不适用于数学函数

时间:2013-10-17 17:31:23

标签: javascript jquery

我正在尝试将4个矩形框转换为sin / cos函数。但它在chrome / firefox中不起作用。但是在IE中,它可以工作。以下是代码,您可以在jsfiddle.

中看到演示
(function() {
    var circle = $(".circle"),
        circleChild = $(".circle-child", circle),
        circleChildLength = circleChild.find("li").length,
        isDragged = false,
        speed = 5,
        angles = [],
        initialDistance = 0,
        totalDistance = 150;

    function moveChildCircles() {
        initialDistance += speed;
        if(initialDistance >= totalDistance  || initialDistance <= 0) {
            speed = -speed; 
            isDragged = !isDragged;
        }

      /* This doesn't work, it works only when I set either translateX or translateY     (not both). */

        circleChild.find("li").each(function(i) {
            $(this).css("transform", "translate(" + initialDistance*Math.cos(angles[i]) + "px," + initialDistance*Math.sin(angles[i]) + "px)");
        });
    }

    circle.click(function() {
        var addAngle = Math.PI*2/circleChildLength;

        for(var i = 0; i < circleChildLength; i++) {
            angles[i] = i*addAngle;
        }   
        isDragged = !isDragged;
    });



    (function animate() {

        requestAnimationFrame(animate);
        if(isDragged) {
            moveChildCircles();
        }
    }());

}());

正如您所看到的,这仅适用于translateX / translateY中的任何一个。当我调试这个, animate()方法仅更新第一个li值。为什么呢?

1 个答案:

答案 0 :(得分:2)

由于数学评估为小数像素,看起来CSS更改无法正常工作。尝试在像素计算中使用Math.round

$(this).css("transform", "translate(" + Math.round(initialDistance*Math.cos(angles[i])) + "px," + Math.round(initialDistance*Math.sin(angles[i])) + "px)");

Demonstration