[英]Find position of element in jquery using .position() not working
I'm doing a simple animation by click a box to move to the right by 100px on each click. 我通过单击一个框来做一个简单的动画,每次单击将其向右移动100px。 And I want that when its position reaches 400, it should move to the left by 100px on each click. 我希望当其位置达到400时,每次单击时它应向左移动100px。
I did a console.log()
but the console only show the initial positioning of the element, and it doesn't update after each click. 我做了console.log()
但是控制台仅显示元素的初始位置,并且每次单击后都不会更新。 I also want the final position to show on the <span id="info">
but it also doesn't update. 我也希望最终位置显示在<span id="info">
但它也不会更新。
Why is that? 这是为什么?
Many Thanks 非常感谢
jquery: 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: HTML:
<div id="somebox">
<a href="#">show</a>
<span id="info">10px</span>
</div>
CSS: 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;
}
Add this to your style sheet: 将此添加到您的样式表:
#somebox a {
position: relative;
}
And on your jQuery where it says marginLeft
, change it to just left
. 在您的jQuery上显示marginLeft
,将其更改为刚好left
。 Do some more tweaking afterwards to get it to show the proper value. 之后再进行一些调整,以显示适当的值。
How about using the .data()
method to make your life easier? 如何使用.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 == '+=' ? '-=' : '+='));
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.