使用.position()查找jquery中元素的位置不起作用

Find position of element in jquery using .position() not working

本文关键字:元素 位置 不起作用 jquery position 查找 使用      更新时间:2023-09-26

我正在做一个简单的动画,每次点击一个框向右移动100像素。我希望当它的位置达到400时,每次点击都应该向左移动100像素。

我做了一个console.log(),但控制台只显示元素的初始位置,每次单击后都不会更新。我也想在<span id="info">上显示最终位置,但它也不会更新。

为什么?

非常感谢

jquery:

$('#somebox > a').click(function(e){
    var thisElem = $(this), 
        aPos = thisElem.position();
    thisElem.animate({ marginLeft: '+=100px' });
    if(aPos.left === 400){
        thisElem.animate({ marginLeft: '-=100px' });
    }
    console.log('finish pos: ' + aPos.left);
    $('#info').text(aPos.left + 'px');
    e.preventDefault();
});

HTML:

<div id="somebox">
  <a href="#">show</a>
  <span id="info">10px</span>
</div>

CSS:

#somebox{
  position: relative;
  background: #EEF0EB;
  border: 1px solid #dedbd7;
  height: 300px;
  width: 500px;
}
#somebox a{
  display: block;
  color: #fff;
  font-weight: bold;
  border: 1px solid #099;
  background: #0C9;
  padding: 5px;
  width: 50px;
  text-decoration: none;
}
#info{
  display: block;
  font-size: 36px;
  color: #777;
  font-weight: bold;
  width: 100px;
  margin: 100px auto;
}

使用.data()方法让你的生活更轻松怎么样?

$('#somebox > a').click(function(e){
    var $this = $(this);
    var rel = $this.data('rel') || '+=';
    var step = 100,  // amount to move each click
        min = 0,     // minimum left movement
        max = 400;   // maximum right movement

    $this.animate({ marginLeft: rel + step + 'px' },function(){
        var margin = parseInt($this.css('margin-left'),10);
        if (margin <= min || margin >= max){
            $this.data('rel',(rel == '+=' ? '-=' : '+='));
        }
    });
});

DEMO

将其添加到您的样式表中:

#somebox a {
 position: relative;
}

在您的jQuery中,它显示marginLeft,将其更改为仅left。之后再做一些调整,使其显示正确的值。