创建一个HTML/JS插件在ES6 -如何刷新DOM节点
Creating a HTML/JS "plugin" in ES6 - how to refresh DOM nodes
我目前正在学习ES6。我试图创建一个carousel,我通常会写作为一个JQuery插件,但现在,而不是写它作为一个ES6模块,以便它可以添加到一个页面的JS使用导入关键字。
由于旋转木马的幻灯片是绝对位于彼此的顶部,因此在JS中进行计算以确定最高的旋转木马幻灯片高度,然后将此高度应用于旋转木马的UL元素。
模块在构造函数中从DOM中获取几个元素,例如包含所有carousel元素的DIV、carousel幻灯片的UL等。
class Carousel {
// set up instance variables
constructor (options) {
this.element = options.element;
this.carousel = options.element.querySelectorAll('ul');
this.carouselSlides = this.carousel[0].children;
this.carouselHeight = 0;
}
resize () {
console.log(this.carouselSlides);
//Get tallest slide
Array.prototype.map.call( this.carouselSlides, ( slide ) => {
this.carouselHeight = (slide.offsetHeight > this.carouselHeight) ? slide.offsetHeight : this.carouselHeight;
});
//Set the height of the carousel to the height of its tallest slide
this.carousel[0].style.height = this.carouselHeight+'px';
}
// initial set up
setup () {
this.resize();
window.onresize = this.resize;
}
}
module.exports = Carousel;
由于这个高度需要随着浏览器宽度变小而调整,我已经尝试调用window.onresize.
上的函数来进行计算。然而,这不起作用。我相信这是因为在构造函数中分配给变量的dom节点被缓存为当前的宽度和高度,因此resize函数不会在计算中使用它们的新值。
我如何调整我的代码来防止这个缓存问题?
下面是到目前为止我的代码的简化代码。(我必须在Codepen的主脚本中添加Carousel模块代码):
http://codepen.io/decodedcreative/pen/vXzGpE/谢谢
您的问题与this
的上下文有关。当您将回调分配给window.resize
事件时,this将更改为window
:
window.onresize = this.resize;
当回调被调用时,this.carouselSlides
是未定义的,因为窗口没有这个属性(查看控制台以查看错误)。
为了防止这个问题,将回调绑定到原来的this
(类实例):
window.onresize = this.resize.bind(this);
你可以在这个代码中看到
原来我的代码有几个问题。多亏了奥里·德罗里的帮助,我找到了真相。下面是固定的代码:
class Carousel {
// set up instance variables
constructor (options) {
this.element = options.element;
this.carousel = options.element.querySelectorAll('ul');
this.carouselSlides = this.carousel[0].children;
this.carouselHeight = 0;
}
resize () {
//Get tallest slide
Array.prototype.map.call( this.carouselSlides, ( slide ) => {
this.carouselHeight = (slide.offsetHeight > this.carouselHeight) ? slide.offsetHeight : this.carouselHeight;
});
//Set the height of the carousel to the height of its tallest slide
this.carousel[0].style.height = this.carouselHeight+'px';
//Reset the height of the carousel to zero
this.carouselHeight = 0;
}
// initial set up
setup () {
this.resize();
window.addEventListener("resize", this.resize.bind(this));
}
}
希望这能帮助到一些人!
相关文章:
- 强制模板刷新ember.js
- 如何通过ajax刷新JSF填充的javascript变量
- 如何解决Yii中的页面刷新问题
- Jquery提交表单而不刷新
- 刷新页面后会出现警报
- 刷新后保留对网页的更改
- 如何在不刷新页面的情况下更新显示框
- 重定向时角度刷新浏览器
- 如何防止jQueryonclick事件中的Ruby方法在页面刷新时执行
- Javascript,输出结果后页面不断刷新
- $(document).height()在刷新时随机化值(Safari 5.1.10)
- 刷新父窗口后无法关闭窗口
- 刷新页面时hasClass不起作用
- X秒后刷新select元素
- chart.series[id].remove()无法刷新高位图表/高位股票中其他系列的图例属性
- 触发媒体查询断点时刷新页面
- 如何刷新列表框内容onclick或blur事件
- 如何在火狐浏览器中禁用F5和刷新
- 如何使用部分刷新刷新一系列面板
- 如何要求浏览器刷新(刷新)我的网站的缓存