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

标签 javascript jquery html css

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

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

这是为什么?

非常感谢

j查询:

$('#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

关于javascript - 使用 .position() 查找元素在 jquery 中的位置不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6374572/

相关文章:

jquery - 将 div 的内容重叠在其他内容上

javascript - 如何获取特定 id 的 Restful 数据

c# - Jquery 隐藏/显示 svg 图像

javascript - jQuery 点击事件为空

javascript - 如何使用 history js 在浏览器中启用/禁用 "click to go forward"按钮?

html - 生成定制的静态 swagger 文档

javascript - 无法呈现对 html div 的 promise 响应

javascript - 阻止 Mathjax 渲染

javascript - Javascript 不适用于 chrome 上的元素 id,但适用于名称(在 Edge 上效果很好)

html - 并非所有列表项都正确排列