前端小白写了个导航栏组件,各位前辈给点意见看看需要怎么改进?

function Navigation(container) {

    this.defaultConfig = {
        container: container,
        prop: [
            {value: '0', color: 'red'},
            {value: '1', color: 'blue'},
            {value: '2', color: 'blue'},
            {value: '3', color: 'blue'}
        ],

        fontColor: 'white',
        fontSize: '20px',
        align: 'center',
    };


    this.init = function () {
        this.createList();
        this.defaultConfig.container.children[0].isClick = false;
        this.defaultConfig.container.children[0].addEventListener('click', function () {
            this.isClick = !this.isClick;
            if (this.isClick) {
                this.parentNode.style.height = this.offsetHeight + 'px';
            }else{
                this.parentNode.style.height = 200 + 'px';
            }
        })
    }


}

Navigation.prototype.createList = function () {
    for (var i = 0; i < this.defaultConfig.prop.length; i++) {
        var div = document.createElement('div');
        div.innerHTML = this.defaultConfig.prop[i].value;
        div.style.color = this.defaultConfig.fontColor;
        div.style.fontSize = this.defaultConfig.fontSize;
        div.style.backgroundColor = this.defaultConfig.prop[i].color;
        div.style.textAlign = this.defaultConfig.align;
        div.style.width = 200 + 'px';
        div.style.height = 50 + 'px';
        div.style.lineHeight = 50 + 'px';
        div.style.border = '1px solid';
        this.defaultConfig.container.appendChild(div);
    }

}

前端小白,学了一段时间JS,只做了最主要的功能,其他一些小功能就没写了。总感觉自己写的代码很不好,但又不知道需要怎么改进,希望各位前辈给点指导意见。

阅读 1.6k
1 个回答

貌似题主不是一位前端,所以我推荐直接用jquery

如一个导航,差不多就是这样的代码

<div class="nav">
    <div class="nav-li"></div>
    <div class="nav-li"></div>
</div>
.nav-li.is-active {
     color: white;
     font-size: 20px;
     text-align: center;
}
var ACTIVE_CLASS = 'is-active'
var $navLi = $('.nav-li');
$navLi.on('click', function() {
    $navLi.removeClass(ACTIVE_CLASS);
    $(this).addClass(ACTIVE_CLASS);
});

即使用原生代码,也推荐激活导航后,为激活的导航添加一个class,关于样式的变更写在css里面,以实现动作和样式分离。

另外,假如想封装组件,2019年还是推荐用vue或react等前端框架。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题