Динамическое изменение размеров элементов с использованием javascript и атрибутов element.style - PullRequest
0 голосов
/ 03 мая 2018

Я пытался найти это, но не могу найти ответы.

Подробности: Я пытаюсь построить карусель javascript без использования каких-либо библиотек. Моя реализация, вероятно, не самая лучшая. То, что я решил сделать, это иметь длинный div.carousel-track, который содержит много .carousel-элементов (эти элементы создаются из объекта в javascript). Трек .carousel шире, чем страница, и имеет переполнение: скрыт, поэтому я могу выбрать один элемент на странице за раз.

Поскольку я использую загрузчик для проекта, в котором он находится, мне нужно, чтобы он выровнялся с контейнерами и столбцами начальной загрузки. Я делаю это по:

  • Получение внутренней ширины окон, деление на 12 и сохранение.
  • При создании .carousel-элементов я использую это число для установки ширины и полей.

The probelm: Это работает изначально, но когда я пытаюсь изменить размер страницы и изменить размеры элементов, это не так, и вместо этого остается со старым значением. Переменная, которая устанавливает ширину, изменяется при изменении размера, так почему же элементы не отображаются при их рендеринге?

            // Set global variables for the window.
        var w = document.defaultView,
            d = document,
            e = document.documentElement,
            g = d.getElementsByTagName('body')[0],
            x = w.innerWidth || e.clientWidth || g.clientWidth,
            y = w.innerHeight || e.clientHeight || g.clientHeight;

        // Set the initial size of the bootstrap grid column for dynamic elements.
        var colOne = x / 12;

        window.addEventListener("optimizedResize", function () {
            console.log('optimizedResize firing');
            w = document.defaultView,
                d = document,
                e = document.documentElement,
                g = d.getElementsByTagName('body')[0],
                x = w.innerWidth || e.clientWidth || g.clientWidth,
                y = w.innerHeight || e.clientHeight || g.clientHeight;
            // Reset the size of bootsrap columns depending on the screen.
            colOne = x / 12;
            console.log(`x: ${x}, col-one: ${colOne}`);
            view.infinite.resize();
        });


        var view = {
            infinite: {
                init: function () {
                    console.log(controller.getCurrentItem());
                    this.rightItem = controller.getRightItem();
                    this.centerItem = controller.getCurrentItem();
                    this.leftItem = controller.getLeftItem();

                    this.HTMLparentElement = document.createElement('div');
                    this.HTMLcarouselTrackElement = document.getElementById('carousel-track');

                    // Offset the carousel by 12 bootstrap columns (aka a whole page).
                    this.HTMLcarouselTrackElement.style.transform = "translateX(-" + colOne * 12 + "px)";

                    view.infinite.render();
                },
                render: function () {
                    console.log('rendering');
                    var carouselItems = [this.leftItem, this.centerItem, this.rightItem];

                    // Appends all the items in the carousel list in a row.
                    for (var i = 0; i < carouselItems.length; i++) {

                        this.HTMLcarouselItemContainer = document.createElement('div');
                        // Add classes for styling the carousel container.
                        this.HTMLcarouselItemContainer.classList.add('inner-carousel', 'carousel-item');
                        view.infinite.resize();
                        this.HTMLcarouselItemContainer.appendChild(HTMLprojectGradientOverlay);
                        // Append the whole carousel item to the carousel track.
                        this.HTMLparentElement.appendChild(this.HTMLcarouselItemContainer);
                    }

                    this.HTMLcarouselTrackElement.innerHTML = this.HTMLparentElement.innerHTML;

                },
                resize: function () {
                    // Dynamically set the width + margins to match the bootstrap width.
                    console.log(colOne);
                    this.HTMLcarouselItemContainer.style.width = (colOne * 10) + "px";
                    this.HTMLcarouselItemContainer.style.marginLeft = (colOne) + "px";
                    this.HTMLcarouselItemContainer.style.marginRight = (colOne) + "px";
                    console.log(this.HTMLcarouselItemContainer);
                }
            },

            move: {
                init: function () {
                    console.log('init move');
                    this.rbtn = d.createElement('button');
                    this.lbtn = d.createElement('button');
                    this.HTMLlistCellRight = document.createElement('li');
                    this.HTMLlistCellLeft = document.createElement('li');
                    this.HTMLspanIndicatorElemRight = document.createElement('span');
                    this.HTMLspanIndicatorElemLeft = document.createElement('span');
                    this.rbtn.innerText = "right";
                    this.lbtn.innerText = "left";

                    var HTMLindicatorListElem = document.getElementById('indicator-list');

                    this.HTMLspanIndicatorElemLeft.appendChild(this.lbtn);
                    this.HTMLlistCellLeft.appendChild(this.HTMLspanIndicatorElemLeft);

                    this.HTMLspanIndicatorElemRight.appendChild(this.rbtn);
                    this.HTMLlistCellRight.appendChild(this.HTMLspanIndicatorElemRight);

                    HTMLindicatorListElem.appendChild(this.HTMLlistCellLeft);
                    HTMLindicatorListElem.appendChild(this.HTMLlistCellRight);



                    this.rbtn.addEventListener('click', function () {
                        return function () {
                            controller.rightRotation();
                            view.infinite.init();
                        };

                    }());

                    this.lbtn.addEventListener('click', function () {
                        return function () {
                            controller.leftRotation();
                            view.infinite.init();
                        };

                    }());

                    view.move.render();
                },
                render: function () {

                }
            },
        };
...