通过两种方法创建和更新 CSS

Create and update CSS in two methods

本文关键字:更新 CSS 创建 方法 两种      更新时间:2023-09-26

如何使用下面的创建和更新方法更新宇宙变量 css:

var gravity = {
    universe: function (width, height, color) {
        this._width = width;
        this._height = height;
        this._color = color;
        var universe;
        var create = function () {
            universe = document.createElement("div");
            universe.style.border = "5px solid #DDD";
            universe.style.overflow = "hidden";
            document.body.appendChild(universe);
        };
        var update = function () {
            universe.style.width = this._width + "px";
            universe.style.height = this._height + "px";
            universe.style.backgroundColor = this._color;
        };
        create();
        update();
    }
}

更新方法不起作用。

更新方法"不起作用",因为当您调用它时,this引用窗口对象。如果您希望它工作,一种可能的解决方案是在 Update 方法外部设置 var that = this;,并将对 this 的所有引用替换为方法内部的that

这应该会澄清一些问题