2016-06-19 122 views
0

我提出在此基礎上搗鼓一個div的JavaScript動畫的起點:http://jsfiddle.net/Xw29r/15/
我正在尋找一種方法來從一個精確的點使動畫開始
Top : 10vhLeft : 90vw但我似乎無法找到如何做到這一點,而不將動畫窗外
更改動畫

思考,纔能有一個大衆的大小使用數學一樣($(window).width()/100*9))
。但似乎還沒有工作。
我怎麼能做到這一點?

$(document).ready(function(){ 
    animateDiv(); 

}); 

function makeNewPosition(){ 

    // Get viewport dimensions (remove the dimension of the div) 
    var h = $(window).height() - 50; 
    var w = $(window).width() - 50; 

    var nh = Math.floor(Math.random() * h); 
    var nw = Math.floor(Math.random() * w); 

    return [nh,nw];  

} 

function animateDiv(){ 
    var newq = makeNewPosition(); 
    var oldq = $('.a').offset(); 
    var speed = calcSpeed([oldq.top, oldq.left], newq); 

    $('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){ 
     animateDiv();   
    }); 

}; 

function calcSpeed(prev, next) { 

    var x = Math.abs(prev[1] - next[1]); 
    var y = Math.abs(prev[0] - next[0]); 

    var greatest = x > y ? x : y; 

    var speedModifier = 0.1; 

    var speed = Math.ceil(greatest/speedModifier); 

    return speed; 

} 
+0

它是如何窗外? ...呃,如果你設置'left:90vw'並且窗口小於500px(500px的十分之一是50px),當然它會在外面......然後像這樣使用CSS calc():'left:calc (90vw - 50px);' – LGSon

+0

例如,如果我將'margin-left:90%;'設置爲'div.a',您將看到動畫將從窗口中移出 – Yagayente

+0

當然,還有其他可能將div移出視圖/窗口時發生? ......也許你可以更具體地說明你想要的東西,也許發佈一張預期結果 – LGSon

回答

2

使用CSS計算()這樣的:left: calc(90vw - 50px);,使之留在窗內,只要在窗口比格本身更大。

$(document).ready(function(){ 
 
    animateDiv(); 
 
    
 
}); 
 

 
function makeNewPosition(){ 
 
    
 
    // Get viewport dimensions (remove the dimension of the div) 
 
    var h = $(window).height() - 50; 
 
    var w = $(window).width() - 50; 
 
    
 
    var nh = Math.floor(Math.random() * h); 
 
    var nw = Math.floor(Math.random() * w); 
 
    
 
    return [nh,nw];  
 
    
 
} 
 

 
function animateDiv(){ 
 
    var newq = makeNewPosition(); 
 
    var oldq = $('.a').offset(); 
 
    var speed = calcSpeed([oldq.top, oldq.left], newq); 
 
    
 
    $('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){ 
 
     animateDiv();   
 
    }); 
 
    
 
}; 
 

 
function calcSpeed(prev, next) { 
 
    
 
    var x = Math.abs(prev[1] - next[1]); 
 
    var y = Math.abs(prev[0] - next[0]); 
 
    
 
    var greatest = x > y ? x : y; 
 
    
 
    var speedModifier = 0.1; 
 

 
    var speed = Math.ceil(greatest/speedModifier); 
 

 
    return speed; 
 

 
}
div.a { 
 
    top: 10vh; 
 
    left: calc(90vw - 50px); 
 
    width: 50px; 
 
    height:50px; 
 
    background-color:red; 
 
    position:fixed; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class='a'></div>