每次我点击拖动太阳时,最初位于太阳左侧的月亮会移动到太阳的右侧。我没有把它放在我的CSS中任何地方把它放在那个位置。我不确定为什么这样做。 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; }
}
#moon {
position: absolute;
width: 500px;
height: 500px;
top: 3%;
left: -10%;
}
#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="moon" src="http://i.imgur.com/o7cwLDa.png">
<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")
var moon = $("#moon")
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({
opacity: 1-(x/total),
marginTop: heightPct * 30 + "%"
});
moon.css({
left:x -(sun.width()/2),
marginTop: heightPct * 30 + "%"
});
$(this).css({
opacity: 1-(x/total),
marginTop: heightPct * 30 + "%"
});
}
});
</script>
</html>
答案 0 :(得分:0)
你有这个:
var x = sun.offset().left + (sun.width() / 2);
...
moon.css({
left:x -(sun.width()/2)
});
当您将sun.width() / 2
添加到left
然后稍后减去它时,您将离开left
。你可以提出:
moon.css({
left: sun.offset().left
});
您的月球图像宽度为500px,但您的太阳图像宽度仅为300px。图像的实际月亮部分大小与太阳图像大致相同,但有额外的填充,将月亮向右推进。
由于它们的左上角位于同一位置,因此月亮出现在太阳的右侧,因为它更宽。