开发者

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

开发者 https://www.devze.com 2023-03-13 06:33 出处:网络
I\'m doing a simple animation by click a box to move to the right by 100px on each click. And I want that when its position reaches 400, it should move to the left by 100px on each click.

I'm doing a simple animation by click a box to move to the right by 100px on each click. And I want that when its position reaches 400, it should move to the left by 100px on each click.

I did a console.log() but the console only show the initial positioning of the element, and it doesn't update after each click. I also want the final position to show on the <span id="info"> but it also doesn't update.

Why is that?

Many Thanks

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;
}


How about using the .data() method to make your life easier?

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


Add this to your style sheet:

#somebox a {
 position: relative;
}

And on your jQuery where it says marginLeft, change it to just left. Do some more tweaking afterwards to get it to show the proper value.

0

精彩评论

暂无评论...
验证码 换一张
取 消