[英]How to set a div position to depend on another div position?
This is the html part of the code: 这是代码的html部分:
<div class="snake">
<div class="body"></div>
</div>
The function below takes the last block, removes it and creates another one to put it at the top. 下面的函数采用最后一个块,将其删除并创建另一个块以将其置于顶部。
//The snake turns right
var turnRight = function() {
blocks_moved++;
$('.snake').children().last().remove();
$('<div></div>').addClass('body').prependTo('.snake').css('top', 0 + '%').css('left', xPos * blocks_moved * 1.2 + '%');
$('.snake').children().removeClass('head');
$('.snake').children().first().addClass('head');
...more code
With the code below I tried to set the snake position eqal to head's position so every time a new block becomes the head the snake moves by one block. 使用下面的代码,我试图将蛇位置eqal设置为头部的位置,因此每当一个新的块成为头部时,蛇就会移动一个块。
//Set the snake position equal to head's position
var headPos = $('.snake').children().first().position();
$('.snake').position(headPos);
if (blocks_moved === length) {
blocks_moved === 0;
}
}
When I call the function turnRight();
当我调用函数turnRight();
the head and body move but snake stays in place. 头部和身体移动,但蛇留在原地。 I also tried with .css()
method but I didn't succeed. 我也试过.css()
方法,但我没有成功。 Any other ways to do this? 还有其他方法吗?
I solved this problem with .offset() and positioning. 我用.offset()和定位解决了这个问题。 Here is a live example: https://jsfiddle.net/dusth7gc/3/ 这是一个实例: https : //jsfiddle.net/dusth7gc/3/
solved this problem with .offset() and positioning. 用.offset()和定位解决了这个问题。
var turnRight = function() {
$('.body').css('background-color', 'gray');
headPos_x = ($('.head').offset().left / $(window).width() * 100);
headPos_y = ($('.head').offset().top / $(window).height() * 100);
$('<div></div>').addClass('body').prependTo('.snake').css('top', headPos_y + '%').css('left', headPos_x + helper_width * 1.2 + '%');
$('.snake').children().last().remove();
$('.snake').children().removeClass('head');
$('.snake').children().first().addClass('head');
$('.helper').css('top', $('.head').offset().top + 'px').css('left',$('.head').offset().left + 'px');
if(collision($('.helper'), $('.meal')) === true) {
$('.meal').remove();
$('<div></div>').addClass('body').css('background-color', 'transparent').appendTo('.snake');
foodCreate();
}
}
Here is a live example: https://jsfiddle.net/dusth7gc/3/ . 这是一个实例: https : //jsfiddle.net/dusth7gc/3/ 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.