2013-01-17 42 views
1

我有jQuery animate 的示例代碼,我想根據時間自動根據計數器擴展div,因爲計數器或時間變化div變寬。我無法弄清楚如何使用一個變量來代替寬度:「70%」動態/連續變化寬度的div或跨度

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
    <head> 
    <meta name="generator" content="HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> 
<style type="text/css"> 
div { 
background-color:#bca;width:100px;border:1px solid green; 
} 
</style> 
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"> 
</script> 
    <title></title> 
    </head> 
    <body> 
    <button id="go">» Run</button> 
    <div id="block"> 
     Hello! 
    </div> 
<script type="text/javascript"> 
/* Using multiple unit types within one animation. */ 
$("#go").click(function(){ $("#block").animate({ width: "70%", opacity: 0.4, marginLeft: "0.6in", fontSize: "3em", borderWidth: "10px" }, 1500);}); 
</script> 
    </body> 
</html> 
+0

看起來你是一個良好的開端。您是否有任何研究或其他代碼來證明您嘗試尋找您正在尋找的解決方案? –

回答

0

請示例代碼使用一個變量寬度:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
    <head> 
    <meta name="generator" content="HTML Tidy for Windows (vers 14 February 2006), see www.w3.org"> 
<style type="text/css"> 
div { 
background-color:#bca;width:100px;border:1px solid green; 
} 
</style> 
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"> 
</script> 
    <title></title> 
    </head> 
    <body> 
    <button id="go">» Run</button> 
    <div id="block"> 
     Hello! 
    </div> 
<script type="text/javascript"> 
    var someWidth = "70%"; 
/* Using multiple unit types within one animation. */ 
$("#go").click(function(){ $("#block").animate({ width: someWidth, opacity: 0.4, marginLeft: "0.6in", fontSize: "3em", borderWidth: "10px" }, 1500);}); 
</script> 
    </body> 
</html> 
+0

感謝您的幫助,我想出了以下鏈接中發佈的代碼。 animate部分工作正常,但它不能在鏈接上工作,因爲它不會拉動外部javascripts。當你點擊這些框時,你可以設置框的背景顏色。我的問題是,如何保存用戶顏色選擇,以便在用戶下次打開此網頁時自動使用它們。該頁面將從本地硬盤驅動器打開,而不是從Web服務器打開。我需要cookie或本地存儲來使用Chrome和IE8 [link] http://jsfiddle.net/3m4uF/ [link] – user1892770

0

您可以通過使用相對動畫指定+=如下

$("#go").click(function(){ 
     $("#block").animate({ 
          width: "+=5%", 
          opacity: 0.4, 
          marginLeft: "0.6in", 
          fontSize: "3em", 
          borderWidth: "10px" 
          }, 1500); 
     }); 

這將5%擴大DIV每一次函數called.Adjust它滿足您的需要。 相反,如果您想間隔地調用animate,請在setInterval中調用此函數。這將每隔2000毫秒調用animate

setInterval(function(){ 

     $("#block").animate({ 
          width: "+=5%", 
          opacity: 0.4, 
          marginLeft: "0.6in", 
          fontSize: "3em", 
          borderWidth: "10px" 

        }, 1500);    

      },2000);