错误是_this.offset
不是函数。我将其记录到控制台,它是 <li>
我点击的元素,所以我很困惑为什么这不起作用。
$('.item').click(function(e) {
var _this = this;
var topx = _this.offset().top;
var leftx = _this.offset().left;
var moveArea = $('#replace').offset().top;
var moveLeft = $('#replace').offset().left;
var moveUp = topx - moveArea - 50;
_this.css('position', 'absolute').css('top', moveUp).css('zIndex', 50).css('left', leftx);
_this.animate({
top: -50,
left: moveLeft
}, 300)
});
#replace {
height: 50px;
width: 100px;
background-color: green;
}
#list {
height: 200px;
overflow-y: scroll;
}
.item {
height: 50px;
width: 100px;
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div id="replace">
Replace this
</div>
<ul id="list">
<li class="item">TEST</li>
<li class="item">TEST</li>
<li class="item">TEST</li>
</ul>
我还想创建一个动画,使我在列表中单击的元素向上移动以替换绿色的“替换此”框,如果有人也可以提供帮助的话。
我创建了一个 jsfiddle 来显示错误:https://jsfiddle.net/v5fjjwmj/2/
最佳答案
this
(因此 _this
)在您的事件处理程序中引用了一个没有 offset()
方法的 DOMElement,因为它是jQuery 的一部分。要解决此问题,您可以使用 $(this)
创建一个 jQuery 对象:
$('.item').click(function(e) {
var $this = $(this);
var topx = $this.offset().top;
var leftx = $this.offset().left;
var moveArea = $('#replace').offset().top;
var moveLeft = $('#replace').offset().left;
var moveUp = topx - moveArea - 50;
$this.css({
'position': 'absolute',
'top': moveUp,
'zIndex': 50,
'left': leftx
}).animate({
top: -50,
left: moveLeft
}, 300)
});
还要注意提供给单个 css()
调用的对象的使用,而不是对同一方法的多次调用。
关于javascript - this.offset 不是点击函数中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36722979/