...">

How to set div position to depend on another div position?

This is the html part of the code:

<div class="snake"> <div class="body"></div> </div> 

The function below takes the last block, removes it and creates another one to place 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 

In the code below, I tried to set the eqal position of the snake position to the head position, so every time a new block becomes a head, the snake moves one block.

 //Set the snake position equal to head position var headPos = $('.snake').children().first().position(); $('.snake').position(headPos); if (blocks_moved === length) { blocks_moved === 0; } } 

When I call the function turnRight(); , the movement of the head and body moves, but the snake remains in place. I also tried using the .css() method, but I failed. Any other ways to do this?

I solved this problem with .offset () and positioning. Here is a live example: https://jsfiddle.net/dusth7gc/3/

+5
source share
1 answer

solved this problem with .offset () and positioning.

 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/ .

0
source

Source: https://habr.com/ru/post/1210560/


All Articles