我正在创建一个游戏,其中有三个杯子,需要洗牌。我为游戏创建了HTML和CSS,但我仍然坚持用Javascript移动三个杯子。
问题是两个杯子需要互相切换,而且有洗牌效果。(你看到杯子移动的效果)我已经发现了一些关于洗牌的信息,但是你没有看到洗牌效果。我希望有人能帮我。
这是我尝试过的代码,它起了作用,但当然没有达到我所需要的效果。
$(document).ready(function(){
$("#start").bind('click', shuffle);
function shuffle(){
$(".cupBox").each(function(){
var divs = $(this).find('div');
for(var i = 0; i < divs.length; i++) $(divs[i]).remove();
//the fisher yates algorithm, from http://stackoverflow.com/questions/2450954/how-to-randomize-a-javascript-array
var i = divs.length;
if ( i == 0 ) return false;
while ( --i ) {
var j = Math.floor( Math.random() * ( i + 1 ) );
var tempi = divs[i];
var tempj = divs[j];
divs[i] = tempj;
divs[j] = tempi;
}
for(var i = 0; i < divs.length; i++) $(divs[i]).appendTo(this);
});
}
});链接到JsFiddle
提前感谢!
发布于 2016-01-15 08:24:04
一种方法是使杯子相对位置,并将css动画放在右侧和左侧位置。然后你给一个杯子另一个杯子的位置,另一个杯子的位置。
看起来会是这样的:
JS:
$(document).ready(function(){
$("#start").on('click', shuffle);
});
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffle(){
var cups = $(".cupBox").find('.cup');
var cup1 = $(cups[getRandomInt(0,cups.length - 1)]);
var cup2 = $(cups.not(cup1)[getRandomInt(0,cups.length - 2)]);
var cup1Offset = cup1.offset();
var cup2Offset = cup2.offset();
cup1.offset(cup2Offset);
cup2.offset(cup1Offset);
}CSS:
.cup {
position : relative;
left : 0;
right : 0;
transition : all linear 2s;
}我已经更新了你的jsFiddle作为演示
增编
但是,因为您可能需要多个动画,所以jQuery动画可能更适合,因为您可以在它的轨道上停止这个动画。如果这是您想要的,您可以尝试使用jQuery stop函数和jQuery animate函数:
会导致这样的结果。转换将再次从css中删除:
JS:
$(document).ready(function(){
$("#start").bind('click', shuffle);
});
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffle(){
//get all the cups!
var cups = $(".cupBox").find('.cup');
//get a random cup depending on cup length
var cup1 = $(cups[getRandomInt(0,cups.length - 1)]);
//get -another- random cup, and make sure it is not the same
var cup2 = $(cups.not(cup1)[getRandomInt(0,cups.length - 2)]);
//stop the animations and skip to the end, otherwise you might get the wrong offset
cup1.stop(false, true);
cup2.stop(false, true);
//obtain both offsets
var cup1Offset = cup1.offset();
var cup2Offset = cup2.offset();
//switch positions while animating for 500ms
cup1.animate({left: '+=' + (cup2Offset.left - cup1Offset.left)}, 500);
cup2.animate({left: '+=' + (cup1Offset.left - cup2Offset.left)}, 500);
}CSS:
.cup {
position : relative;
left : 0;
right : 0;
}下面是一个更新的jsFiddle
https://stackoverflow.com/questions/34806680
复制相似问题