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,只做了最主要的功能,其他一些小功能就没写了。总感觉自己写的代码很不好,但又不知道需要怎么改进,希望各位前辈给点指导意见。
貌似题主不是一位前端,所以我推荐直接用
jquery
:如一个导航,差不多就是这样的代码
即使用原生代码,也推荐激活导航后,为激活的导航添加一个class,关于样式的变更写在css里面,以实现动作和样式分离。
另外,假如想封装组件,2019年还是推荐用vue或react等前端框架。