我有这段代码:
var viewport = $(window),
viewport_height = viewport.height();
var _topPanel = jQuery.extend({
el: $('.js-lp_top'),
//
height: function() {
var self = this;
self.el.css('min-height', viewport_height);
},
scroll : function() {
var self = this;
var scrolled = viewport.scrollTop();
viewport.on('scroll', function() {
self.el.css({
'top': (49 - (scrolled / viewport_height) * 80) + '%'
});
});
}
});
var topPanel = new _topPanel.height().scroll();
jQuery错误Cannot read property 'css' of undefined
。我做错了什么?求助。
答案 0 :(得分:1)
让我们先来看看这行代码。
var topPanel = new _topPanel.height().scroll();
关键字new
会创建一个新的空对象。在height
函数中,this
关键字引用了这个新对象,当然它没有el
属性。 self.el
未定义,因此出现错误消息Cannot read property 'css' of undefined
这里有两个变化:
确保您的height
和scroll
函数返回this
,以支持函数链
调用new
函数时不要包含height
关键字
以下是修改后的代码:
var _topPanel = jQuery.extend({
el: $('.js-lp_top'),
//
height: function () {
var self = this;
self.el.css('min-height', viewport_height);
return self;
},
scroll: function () {
var self = this;
var scrolled = viewport.scrollTop();
viewport.on('scroll', function () {
self.el.css({
'top': (49 - (scrolled / viewport_height) * 80) + '%'
});
});
return self;
}
});
var topPanel = _topPanel.height().scroll();