即使我在窗口事件之前缓存了“this”,我也无法访问我的 DOM 选择器。
如果我将其更改为 $('.banner')
,它就可以工作。
之前在我的代码中,我在窗口事件上设置了 scrolltop
变量 scrolled
,我可以在我的 scrollEvent()
方法中使用它module.scrolled
。
此外,CSS 中的不透明度规则不起作用。
顶部和相对位置是。
var parallax = {
init: function() {
this.cacheDom();
this.scrollEvent();
},
cacheDom: function() {
var $window = $(window),
banner = $('.banner'),
callout = $('.callout'),
bannerHeight = Math.round(banner.outerHeight()),
hideElem = false,
hasScrolled = false,
scrolled;
},
scrollEvent: function() {
var module = this;
$(window).on('scroll', function() {
var scrollTop = $(this).scrollTop();
module.banner.css("background-position", '50%' + (scrollTop / 1.75) + "px");
module.callout.css({'position': 'relative', 'top' : scrollTop * 0.75, 'opacity' : 1 - (scrollTop / module.bannerHeight * 2)});
});
}
};
parallax.init();
最佳答案
cacheDom()
函数正在设置局部变量,而不是对象属性。将其更改为:
cacheDom: function() {
this.$window = $(window);
this.banner = $('.banner');
this.callout = $('.callout'),
this.bannerHeight = Math.round(this.banner.outerHeight());
this.hideElem = false;
this.hasScrolled = false;
this.scrolled = null;
},
关于javascript - 无法使用对象文字模块模式访问变量并应用某些 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44338553/