javascript函数rotate元素=>尝试为传入的特定参数设置IF条件

javascript function rotate element => trying to set an IF condition for a specific parameter passed in

本文关键字:参数 条件 IF 设置 元素 rotate 函数 gt javascript      更新时间:2023-09-26

我需要旋转两个div块,一个顺时针旋转,另一个逆时针旋转。我已经有了第一个集合,使用var STEP,我可以通过给它正值/负值来选择哪个方向。现在,由于我已经知道第二个div参数startUpProc('fourSquares3')的ID,我尝试创建一个if语句,检查是否传递了参数"fourSquares3",并将全局var STEP设置为相反的值(在这种情况下,假设为正),但它就是不起作用,即使使用if,在我运行它的最后,它们都以相同的方式运行。

所以我的问题是:我如何正确地更改代码,以便如果传递了特定的参数,它将打开CCW。

这是我的代码:

startUpProc('fourSquares');

var STEP = -7;
function startUpProc(id)
{
    var log = window.document.getElementById(id);
    makeCircle(log, 0);
}
function makeCircle(item, targetAngle) {
    changeRotate(item, targetAngle);
    if (targetAngle < 720) {
        setTimeout(function (){
            makeCircle(item, targetAngle + STEP);
        }, 80);
    }
}
function changeRotate(item, val)
{
    item.style.transform = "rotate(" + val + "deg)";
    item.style.webkitTransform = "rotate(" + val + "deg)";
    item.style.mozTransform = "rotate(" + val + "deg)";
    //alert(item.style.transform);
}

问题是您使用相同的变量(STEP),该变量的值在两个块(div)之间共享。您必须将这个变量封装到执行旋转的代码中。最简单的方法是使用闭包。

在您的情况下,您必须将STEP的声明以及所有使用它的子例程函数放在startUpProc函数中。这确保了startUpProc的每个实例(调用)都将处理其自己的变量实例。此外,最好通过CSS类而不是ID来确定方向的类型。这使您的代码更加灵活,而不依赖于固定的ID值。此外,它还允许将此代码用于多个块(3个或更多),而不是像您的示例中那样仅用于两个块。

var classCcw = 'ccw'; // class indicating counter-clockwise direction
function startUpProc(id)
{
    var log = window.document.getElementById(id);
    var isCcw = (' '+log.className+' ').indexOf(' '+classCcw+' ') >= 0;
    var STEP = isCcw? 7 : -7;
    makeCircle(log, 0);
    function makeCircle(item, targetAngle) {
        changeRotate(item, targetAngle);
        if (targetAngle < 720) {
            setTimeout(function (){
                makeCircle(item, targetAngle + STEP);
            }, 80);
        }
    }
    function changeRotate(item, val)
    {
        item.style.transform = "rotate(" + val + "deg)";
        item.style.webkitTransform = "rotate(" + val + "deg)";
        item.style.mozTransform = "rotate(" + val + "deg)";
        //alert(item.style.transform);
    }
}
startUpProc('square1');
startUpProc('square2');
startUpProc('square3');

HTML代码示例:

<div id="square1" class="ccw">
<div id="square2">
<div id="square3" class="ccw">

所有对函数的调用都将使用可变STEP的相同实例,如果你改变它,它们都会改变。

如果你想要不同的方向,你必须把它分开,类似这样的东西:

function makeCircle(item, targetAngle) {
    changeRotate(item, targetAngle);
    var direction = 1;
    //condition 
    if (item=='whatver') 
      direction = -1;
    if (targetAngle < 720) {
        setTimeout(function (){
            makeCircle(item, targetAngle + STEP * direction);
        }, 80);
    }
}