[英]Error: Cannot read property 'top' of undefined
I need help with this since it's showing and I tried with global variable etc an issue remains.. 我需要帮助,因为它正在显示,并且我尝试使用全局变量等问题。
var $ = jQuery;
var $window = $(window),
$moving1 = $(".scroller1"),
$holder1 = $("#scroller-wrap1"),
offset1;
$window.load(function() {
offset1 = $holder1.offset();
});
$window.scroll(function() {
if ($window.scrollTop() > offset1.top) {
$moving1.addClass('fixed');
} else {
$moving1.removeClass('fixed');
}
if ($window.scrollTop() > (offset1.top + $holder1.height() - $moving1.height() - 60)) {
$moving1.removeClass('fixed', 1000);
}
//console.log("scroll: " +$window.scrollTop());
});
Basically I am checking if the windows if fully loaded so I can make the calculations without error but I guess it's not correct. 基本上,我正在检查Windows是否已完全加载,因此我可以进行计算而不会出现错误,但我认为这是不正确的。
This is inside wordpress that's why I need the jQuery part. 这是在wordpress内部的,这就是为什么我需要jQuery部分的原因。
Ok. 好。 The error is coming from this command:
错误来自以下命令:
if ($window.scrollTop() > offset1.top) {
and it means that offset1
is undefined
. 这意味着
offset1
是undefined
。 Now, you are initializing offset1
in your .load
event, but you are setting it equal to $holder
and $holder1
is initialized before the document is ready, so it becomes undefinded
. 现在,要初始化
offset1
在.load
事件,但要设置它等于$holder
和$holder1
文档之前准备好被初始化,所以它成为undefinded
。
Your code can be reduced greatly by just adding a document.ready
function. 只需添加
document.ready
函数,即可大大减少代码。 You also don't have to do this var $ = JQuery
as that is automatic.: 您也不必这样做
var $ = JQuery
因为它是自动的。
// Passing a function to JQuery creates a "document.ready()" callback // function that will automatically be executed when the DOM is built. $(function(){ var $window = $(window); var $moving1 = $(".scroller1"); var $holder1 = $("#scroller-wrap1"); var offset1 = $holder1.offset(); // JQuery recommends the use of the .on() function to bind // event callbacks as opposed to event methods. $window.on("scroll", function() { if ($window.scrollTop() > offset1.top) { $moving1.addClass('fixed'); } else { $moving1.removeClass('fixed'); } if ($window.scrollTop() > (offset1.top + $holder1.height() - $moving1.height() - 60)) { $moving1.removeClass('fixed', 1000); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.