类写法和构造函数写法实现选项卡案例

布局:

    <div class="container1">
        <ul>
            <li class="active">1li>
            <li>2li>
            <li>3li>
            <li>4li>
            <li>5li>
        ul>

        <ol>
            <li class="active">11111li>
            <li>22222li>
            <li>33333li>
            <li>44444li>
            <li>55555li>
        ol>
    div>

样式:


类实现:

class Tabs {
            constructor(className, type) {
                this.container = document.querySelector(className);
                this.headerItems = this.container.querySelectorAll("ul li");
                this.contentItems = this.container.querySelectorAll("ol li");
                this.type = type;

                this.change();
            }

            change = function () {
                for (let i = 0; i < this.headerItems.length; i++) {
                    this.headerItems[i].addEventListener(this.type, () => {
                        for (let n = 0; n < this.headerItems.length; n++) {
                            this.headerItems[n].classList.remove("active");
                            this.contentItems[n].classList.remove("active");
                        }

                        this.headerItems[i].classList.add("active");
                        this.contentItems[i].classList.add("active");
                    }, false)
                }
            };
        }

new Tabs(".container1", 'mouseover');

构造函数实现:

function Tabs(className) {
        this.container = document.querySelector(className);
        this.headerItems = this.container.querySelectorAll("ul li");
        this.contentItems = this.container.querySelectorAll("ol li");

        this.change();
      }

      Tabs.prototype.change = function() {

        for (let i = 0; i < this.headerItems.length; i++) {
          this.headerItems[i].onclick = () => {
            for (let n = 0; n < this.headerItems.length; n++) {
              this.headerItems[n].classList.remove("active");
              this.contentItems[n].classList.remove("active");
            }

            this.headerItems[i].classList.add("active");
            this.contentItems[i].classList.add("active");
          };
        }

      };

      new Tabs(".container1");

你可能感兴趣的:(笔记,javascript,前端,html)