2017-03-03 226 views
0

我正在嘗試在頁面滾動上執行動畫,其中選定元素將從左向右進行動畫向下滾動,如果返回頂部,則爲所選內容設置動畫從右至左(默認位置)元素,這裏就是我試圖動畫向右滾動向下滾動並向左滾動動畫

$(document).ready(function() { 
 
    $(window).scroll(function() { 
 
    var wS = $(this).scrollTop(); 
 

 
    if (wS <= 10) { 
 

 
     $("#test-box").animate({ 
 
     'left': 100 
 
     }, 500); 
 

 
    } 
 
    if (wS > 11) { 
 

 
     $("#test-box").animate({ 
 
     'left': $('#main-container').width() - 100 
 
     }, 500); 
 

 

 
    } 
 

 
    }); 
 

 
});
#main-container { 
 
    width: 100%; 
 
    overflow: auto; 
 
    height: 500px; 
 
} 
 

 
#test-box { 
 
    background: red; 
 
    color: #ffffff; 
 
    padding: 15px; 
 
    font-size: 18px; 
 
    position: fixed; 
 
    left: 100; 
 
    top: 10; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="main-container"> 
 
    <div id="test-box">test</div> 
 
</div>

正如你所看到的,在向下滾動,測試框移動作爲我指示,但是當向上滾動,它不作爲默認去左邊,任何想法,請幫助嗎?

回答

0

您可以添加一個全局變量來控制動畫。請參見下面的代碼片段工作請,在那裏我已經評論說,我加入了部分代碼:

$(document).ready(function() { 
 
    var animated = false; //added variable to control the animation 
 
    $(window).scroll(function() { 
 
    var wS = $(this).scrollTop(); 
 
    if (animated && wS <= 10) { 
 
     $("#test-box").animate({ 
 
     'left': 100 
 
     }, 500); 
 
     animated = false; //animation ended 
 
    } 
 
    if (!animated && wS > 11) { 
 
     $("#test-box").animate({ 
 
     'left': $('#main-container').width() - 100 
 
     }, 500); 
 
     animated = true; //it was animated 
 
    } 
 
    }); 
 
});
#main-container { 
 
    width: 100%; 
 
    overflow: auto; 
 
    height: 500px; 
 
} 
 

 
#test-box { 
 
    background: red; 
 
    color: #ffffff; 
 
    padding: 15px; 
 
    font-size: 18px; 
 
    position: fixed; 
 
    left: 100px; 
 
    top: 10; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="main-container"> 
 
    <div id="test-box">test</div> 
 
</div>

0

這應該工作,它也使用CSS的動畫。

$(document).ready(function() { 
 
    var box = document.querySelector('#test-box'); 
 
    var stateClass = '-right'; 
 
    window.addEventListener('scroll', function(event) { 
 
    box.classList.toggle(stateClass, document.body.scrollTop > 10); 
 
    }); 
 
});
#main-container { 
 
    width: 100%; 
 
    overflow: auto; 
 
    height: 2000px; 
 
} 
 

 
#test-box { 
 
    background: red; 
 
    color: #ffffff; 
 
    padding: 15px; 
 
    font-size: 18px; 
 
    position: fixed; 
 
    left: 100px; 
 
    top: 10; 
 
    transition: .5s linear; 
 
} 
 

 
#test-box.-right { 
 
    left: 100%; 
 
    transform: translateX(-100%) translateX(-100px) 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="main-container"> 
 
    <div id="test-box">test</div> 
 
</div>