我怎样才能从offset()开始;功能反复

时间:2018-01-06 15:00:23

标签: javascript jquery function if-statement offset

所以我花了很多时间来制作这段代码,但它是有效的,但我唯一无法解决的错误就是让它反复循环。任何人都可以提出一些关于这个问题的建议吗?这是解决方案吗?

 <h1 id="heading">Hello</h1>

 var offsetLeft = 0;
 var offsetTop = 0;
 var offsetLeftReverse = 200;
 var offsetTopReverse = 200;

 var moveHeading = function () {
     $("#heading").offset({ left: offsetLeft, top: offsetTop});

    if(offsetLeft < 200){
        offsetLeft++;
    } else if (offsetTop < 200){
        offsetTop++;
    }
 };

var moveHeadingReverse = function () {
     $("#heading").offset({ left: offsetLeftReverse, top: offsetTopReverse});

    if(offsetLeftReverse > 0 ){
        offsetLeftReverse--;
    } else if (offsetTopReverse > 0){
        offsetTopReverse--; 
    } 
 };

var engine = function () {
   if ( (offsetTop === 0 && offsetLeft <= 200) || (offsetTop < 200 && offsetLeft === 200) ){
        moveHeading(); 
    } 
   else if ( (offsetTopReverse === 200 && offsetLeftReverse <= 200) || (offsetTopReverse <= 200 && offsetLeftReverse === 0) &&
            ( offsetTopReverse != 0 || offsetLeftReverse != 0 ) ){
       moveHeadingReverse();
       console.log("reverse");
       console.log(offsetTopReverse,offsetLeftReverse);
    } 
}

var start = setInterval(engine, 5); 

1 个答案:

答案 0 :(得分:2)

试试这个:你必须处理偏移量为0的情况,然后将你的变量重置为启动状态,然后再次调用引擎(为你做了intervall):

var engine = function () {
   if ( (offsetTop === 0 && offsetLeft <= 200) || (offsetTop < 200 && offsetLeft === 200) ){
        moveHeading(); 
    } 
   else if ( (offsetTopReverse === 200 && offsetLeftReverse <= 200) || (offsetTopReverse <= 200 && offsetLeftReverse === 0) &&
            ( offsetTopReverse != 0 || offsetLeftReverse != 0 ) ){
       moveHeadingReverse();
       console.log("reverse");
       console.log(offsetTopReverse,offsetLeftReverse);
    } else if ( offsetTopReverse === 0 && offsetLeftReverse === 0) {
        offsetLeft = 0;
            offsetTop = 0;
            offsetLeftReverse = 200;
            offsetTopReverse = 200;
    }
}

查看小提琴:https://jsfiddle.net/yfp9f70g/