我正在制作一个简单的动画,方法是单击一个框,每次单击时向右移动 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 == '+=' ? '-=' : '+='));
}
});
});
关于javascript - 使用 .position() 查找元素在 jquery 中的位置不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6374572/