search

Home  >  Q&A  >  body text

javascript - Why do I need to customize a property before the delayer of this motion function?

This function is used to create an animation effect:

function moveElement(elementId,final_x,final_y,interval){
//            名称            id       x轴位置    y轴位置   速度
    var elem=document.getElementById(elementId);
    var x_pos=parseInt(elem.style.left);
    var y_pos=parseInt(elem.style.top);
    if(elem.movement){
        clearTimeout(elem.movement);
    }            //若elem已存在一个movement属性,先结束它
    if(y_pos==final_y&&x_pos==final_x){
        return true;
    }
    if(y_pos<final_y){
        dist=Math.ceil((final_y-y_pos)/30);//每运动一次的数值
        y_pos=y_pos+dist;
    }
    if(y_pos>final_y){
        dist=Math.ceil((y_pos-final_y)/30);
        y_pos=y_pos-dist;
    }
    if(x_pos<final_x){
        dist=Math.ceil((final_x-x_pos)/30);
        x_pos=x_pos+dist;
    }
    if(x_pos>final_x){
        dist=Math.ceil((x_pos-final_x)/30);
        x_pos=x_pos-dist;
    }
    elem.style.top=y_pos+"px";
    elem.style.left=x_pos+"px";
    repeat="moveElement('"+elementId+"',"+final_x+","+final_y+","+interval+")"
    elem.movement=setTimeout(repeat,interval)
//  自定义的属性movement,它属于elem
}

Regarding the last sentence elem.movement=setTimeout(repeat,interval)
and the above sentence if(elem.movement){

    clearTimeout(elem.movement);
}

I know that their function is to end the function that was run last time when running again, but why does it report an error when directly writing movement=setTimeout(repeat,interval), and can it be written as elem.movement?

为情所困为情所困2752 days ago451

reply all(1)I'll reply

  • 阿神

    阿神2017-05-19 10:20:30

    movement and elem have a one-to-one correspondence.

    If you write it the way you write it, movement becomes a global variable.

    reply
    0
  • Cancelreply