this.offset不是点击函数内的函数 [英] this.offset is not a function within a click function

查看:800
本文介绍了this.offset不是点击函数内的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个jsfiddle来显示错误。

I created a jsfiddle to show the error.

https://jsfiddle.net/v5fjjwmj/2/

错误是_this.offset不是函数。我控制台记录这是,它是< li> 元素我点击,所以我困惑为什么这将无法工作。

The error is that _this.offset is not a function. I console logged this and it was the <li> element I clicked on, so I am confused why this would not work.

HTML

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

JS:

 $('.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)
});

CSS:

#replace {
  height: 50px;
  width: 100px;
  background-color: green;
}

#list {
  height: 200px;
  overflow-y: scroll;
}

.item {
  height: 50px;
  width: 100px;
  background-color: blue;
}

我还想创建一个动画,

I also want to create an animation such that the item I click in the list moves up to replace the green "Replace this" box, if someone could help with that too.

推荐答案

这个(因此 _this )在你的事件处理程序中引用一个DOMElement没有 offset() 方法作为jQuery的一部分。要解决这个问题,您可以使用 $(this)创建一个jQuery对象:

this (and hence _this) inside your event handler refers to a DOMElement which doesn't have the offset() method as that's part of jQuery. To fix this you can create a jQuery object using $(this):

$('.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 / code>调用同一方法的多个调用。

Also note the use of the object provided to a single css() call over multiple calls to the same method.

这篇关于this.offset不是点击函数内的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆