如何让太阳弧停在页面的左端?

时间:2015-10-17 20:23:45

标签: javascript jquery html css draggable

我让太阳以弧形拖动,但是我希望弧停在某一点,在这种情况下,它是页面的左端。现在它永远在左边继续,但我希望它停止。我怎么能这样做?

var width = 300;
var sun = $("#sun");

sun.draggable({
  axis: "x",
  drag: function() {
    var x = sun.offset().left + (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) + "%";
  }
});
/* 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%;
}
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<img id="dark_sun" src="http://i.imgur.com/f3UFHb7.png">
<img id="sun" src="http://i.imgur.com/DGkZYZQ.png">

1 个答案:

答案 0 :(得分:1)

[0-9]{2}定义中将containment option设置为body(或其他一些容器),并隐藏CSS中draggable上的x溢出:

body
var width = 300;
var sun = $("#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) + "%";
  }
});
/* Colors */

body {
  background: url(http://i.imgur.com/aZty7Mq.png);
  padding: 30px;
  overflow-x: hidden;
  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%;
}