繁体   English   中英

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

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

我通过单击一个框来做一个简单的动画,每次单击将其向右移动100px。 我希望当其位置达到400时,每次单击时它应向左移动100px。

我做了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;
}

将此添加到您的样式表:

#somebox a {
 position: relative;
}

在您的jQuery上显示marginLeft ,将其更改为刚好left 之后再进行一些调整,以显示适当的值。

如何使用.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

暂无
暂无

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

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