2015-10-19 104 views
0

在我的程序中實際上有兩個太陽,但一個太陽又名「dark_sun」就在另一個「太陽」的後面。我希望「太陽」逐漸淡出或在弧線中間逐漸變得不透明(這是我的程序中太陽的方向),所以在弧線的末端只能看到「dark_sun」。我怎麼做?這是程序URL:http://whatisupson.tumblr.com/我如何在拖動元素時逐漸減少元素的透明度?

<style> 
     /* Colors */ 
     body { 
      background: url(http://i.imgur.com/aZty7Mq.png); 
      animation: mymove 4s linear infinite; 
      -webkit-animation: mymove 4s linear infinite; 
      -moz-animation: mymove 4s linear infinite; 
     } 
     @keyframes mymove { 
      0% { background-position: 0 0; } 
      50% { background-position: 40% 0; } 
     } 
     #dark_sun { 
      position: absolute; 
      width: 300px; 
      height: 300px; 
      top: 20%; 
      left: 10%; 
     } 
     #sun { 
      position: absolute; 
      width: 300px; 
      height: 300px; 
      top: 20%; 
      left: 10%; 
     } 
    </style> 

    <html> 
    <body> 
      <img id="dark_sun" src="http://i.imgur.com/f3UFHb7.png"> 
      <img id="sun" src="http://i.imgur.com/DGkZYZQ.png"> 
    </body> 
    <script src="//code.jquery.com/jquery-1.10.2.js"></script> 
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> 
    <script> 
    var width = 300; 
    var sun = $("#sun"); 
    var dark = $("#dark_sun") 

    sun.draggable({ 
     axis: "x", 
     containment: 'body', 
     drag: function() { 
     var x = sun.offset().left + (sun.width()/2); 
     var total = $(window).width(); 
     var heightPct = Math.pow((total/2) - x, 2)/Math.pow($(window).width()/2, 2); 
     console.log(x, $(window).width(), heightPct * 100); 
     this.style["margin-top"] = "" + Math.round(heightPct * 30) + "%"; 

     dark.css({ 
      left:x -(sun.width()/2), 
      marginTop: heightPct * 30 + "%" 
     }); 
     $(this).css({ 
      marginTop: heightPct * 30 + "%" 
     }); 
     } 
    }); 

    </script> 
    </html> 

回答

1

你可以這樣嘗試,相對於窗口的邊界具有不透明度。 小提琴:http://jsfiddle.net/oujq3zpq/

$(this).css({ 
     opacity: 1-(x/total), 
     marginTop: heightPct * 30 + "%" 
    }); 

仍然有改進的餘地,因爲太陽永遠不會用這種方法完全不透明。

+0

謝謝我認爲這是完全正確的,它正是我想要的。另外說我想添加一個第三元素,如月亮,並希望它在弧的最後1/3處可見。我可以只使用相同的方法,它會起作用嗎? –

+1

是的,應該這樣工作,只要讓你的數學正確,它就會工作。如果你需要幫助,你可以再問一次。不用謝。 – Lacrioque

+0

是的,你能幫我調整數學嗎?這是我的新代碼:https://gist.github.com/anonymous/4d1d6d2f2288f7336679 月亮現在落後於兩個太陽。 –

1

你必須做一個函數來「曬」 CSS屬性不透明度值動畫從0.0到1.0。像不透明度=(距左/窗口寬度的距離)