创建一个HTML/JS插件在ES6 -如何刷新DOM节点

Creating a HTML/JS "plugin" in ES6 - how to refresh DOM nodes

本文关键字:何刷新 刷新 DOM ES6 节点 插件 一个 HTML 创建 JS      更新时间:2023-09-26

我目前正在学习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));
     }

}

希望这能帮助到一些人!