我正在编写一个小脚本,以确定某个元素是否在视口中...
我遇到的问题是我的变量RET
总是以UNDEFINED
的形式返回
myscript.js
function myScriptObj() {
this.isElementInView = function (element, fullyInView) {
var RET;
$(window).scroll(function () {
var pageTop = $(window).scrollTop();
var pageBottom = pageTop + $(window).height();
var elementTop = $(element).offset().top;
var elementBottom = elementTop + $(element).height();
if (fullyInView === true) {
RET = (pageTop < elementTop) && (pageBottom > elementBottom);
console.log(`myscript.js: RET >>> ${RET}`);
return RET;
} else {
RET = (elementTop <= pageBottom) && (elementBottom >= pageTop);
console.log(`myscript.js: RET >>> ${RET}`);
return RET;
}
});
console.log(`myscript.js: RET >>> ${RET}`);
}
}
在示例中index.html看起来像
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...
...
<div class="row center" id="banner">
<img src="img/banner.jpg" width="514px" height="65px" border="0" />
</div>
...
<script src="js/myscript.js"></script>
<script type="text/javascript">
var myObj = new myScriptObj();
var _isInView = myObj.isElementInView(document.getElementById("banner"), false);
console.log(`index.html: myObj.RET >>> ${myObj.RET}`);
if (_isInView) {
console.log(`index.html: in view >>> ${_isInView}`);
} else {
console.log(`index.html: out of view >>> ${_isInView}`);
}
</script>
</body>
</html>
同样,myObj.RET
是未定义的,但是,在函数isElementInView
中,变量RET
的值为true或false
有人可以告诉我我在想什么