简体   繁体   English

.offset()并检查jQuery中的位置

[英].offset() and checking the position in jQuery

This is my HTML code: 这是我的HTML代码:

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

In script I have a function that creates body parts and appends them to .snake . 在脚本中,我有一个函数可以创建身体部位并将其附加到.snake

It looks something like this: 看起来像这样:

$('.btn1').click(function() {
    length++;
    $('<div></div>').addClass('body').appendTo('.snake').css('left', xPos * length * 1.2 + '%');   
});

Then another function removes the last body part, creates a new one, puts it on the top and gives it .head class. 然后另一个函数删除最后一个正文部分,创建一个新的正文部分,将其放在顶部,并赋予它.head类。

$('.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');

So every time this function is called new <div> is given the .head class. 因此,每次调用此函数时,都会为.head类指定新的<div>

var headPos = $('.head').offset();
            alert(headPos);

In the two lines of code above I tried to alert .head 's position but I used .offset() so it should alert coordinates depending on document not on parent element. 在上面的两行代码中,我尝试警告.head的位置,但我使用了.offset()因此它应根据文档(而不是父元素.offset()来警告坐标。 This two lines are also in teh function above. 这两行也在上面的功能中。 It alerts something like [object Object]. 它会发出类似[object Object]的警报。 Why isn't this working? 为什么这不起作用? I need this variable so I can set .snake position the same as .head position. 我需要此变量,因此我可以将.snake位置设置为与.head位置相同。

I tried this with $('.snake').position(headPos); 我用$('.snake').position(headPos); but I think that .position() function can't set the position. 但我认为.position()函数无法设置位置。 Any other ways of doing this and some help with .offset() would be great. 这样做的任何其他方式以及.offset()一些帮助都很好。 I'm new to programming so any advices would be helpful. 我是编程新手,所以任何建议都将对您有所帮助。 :) :)

PS 聚苯乙烯

I forgot one more thing. 我忘了一件事。 What about css? 那css呢? Which position values should I use? 我应该使用哪个位置值? I used position: absolute; 我使用的position: absolute; with both head and body parts. 头部和身体各部分。

offset() is an object containing two properties, top and left . offset()是包含两个属性topleft的对象。

use offset().top to get the y position 使用offset().top获取y位置

var headPos_x = $('.head').offset().left;
var headPos_y = $('.head').offset().top;
alert("x:" + headPos_x + ", y:" + headPos_y);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM