我有这段代码;
class toTop {
constructor(topButton) {
this.topButton = topButton;
this.topButton = $('#to_top');
if (this.topButton.length > 0) {
$(window).on('scroll', () => {
return this.toggle($(window));
});
this.topButton.on('click', function(e) {
e.preventDefault();
return window.scrollTo(0, 0);
});
}
}
toggle(trgt) {
if (trgt.scrollTop() > 250) {
return this.topButton.fadeIn();
}
return this.topButton.fadeOut();
}
render(trgt) {
return trgt.append(this.topButton);
}
}
我想知道以下事情;
什么是纯Javascript,仅用于
返回this.toggle($(window))
。我尝试使用这个;window.addEventListener('滚动', function() {
返回 this.toggle($(window));
});
但不工作。
另外,这部分;
toggle(trgt) {
if (trgt.scrollTop() > 200) {
return this.topButton.fadeIn();
}
return this.topButton.fadeOut();
}
render(trgt) {
return trgt.append(this.topButton);
}
我尝试转换为 ES6 但没有成功。如果有人能提供帮助那就太好了。
最佳答案
您尝试的这行代码的问题:
window.addEventListener('scroll', function() { return this.toggle($(window)); });
是您忘记了this
的范围发生了变化。如果您像在 jQuery 示例中那样使用箭头函数,您就已经解决了该问题。
window.addEventListener('scroll', () => { return this.toggle($(window)); });
这也可以通过删除大括号和返回
来缩短一点
window.addEventListener('scroll', () => this.toggle($(window)));
但是你仍然会遇到一个问题,即 $(window)
和 $('#to_top')
不是 JavaScript 原生的,而是 jQuery 的。
与 $(window)
最接近的 native 将是 document.body
,与 $('#to_top')
最接近的将是document.getElementById('to_top')
,但这会破坏 fadeIn
和 fadeOut
,因为它们不是原生 JavaScript,而是 jQuery 的一部分。
关于javascript - $(window) 等效项和其他 Jquery 到 Vanilla JS 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58432423/