用mui編寫一款APP,需實現如下露珠圖,考慮用到原生js編寫,並插件化。
js代碼
(function(win, doc) {
var defaultSettings = {
data: []
};
function DrawDewchart(options) {
var self = this;
//沒傳配置項自己丟錯
if(!options) {
throw new Error("請傳入配置參數");
}
self = Object.assign(self, defaultSettings, options);
self.container = doc.querySelector(self.container) || doc.querySelectorAll(self.container);
self._setContent();
}
DrawDewchart.prototype = {
_setContent: function() {
var self = this;
var chead = doc.createElement("div");
chead.innerHTML = self.title;
chead.setAttribute("class", 'chead');
self.container.appendChild(chead);
var contendiv = doc.createElement("div");
contendiv.setAttribute("class", 'content-body');
self.container.appendChild(contendiv);
var cbody = doc.createElement("div");
cbody.setAttribute("class", 'cbody');
contendiv.appendChild(cbody);
var arr = {
total: 1,
count: []
};
var dd = 1;
arr.odd = self.data[0];
if(arr.odd == self.label[0]) {
arr.even = self.label[1];
} else {
arr.even = self.label[0];
}
//self.container
self.data.forEach(function(val, idx) {
if(idx > 0) {
if(val == self.data[idx - 1]) {
dd++;
} else {
arr.count.push(dd);
dd = 1;
arr.total++;
}
}
if(idx == self.data.length - 1) {
arr.count.push(dd);
}
});
//
arr.count.forEach(function(val, idx) {
var div = doc.createElement("div");
for(var i = 0; i < val; i++) {
var span = doc.createElement("span");
if(idx % 2 == 0) {
span.innerHTML = arr.odd;
if(arr.odd == self.red) {
span.setAttribute("class", 'red');
}
} else {
span.innerHTML = arr.even;
if(arr.even == self.red) {
span.setAttribute("class", 'red');
}
}
div.appendChild(span);
}
cbody.appendChild(div);
cbody.style.width = arr.count.length * 30 + 30 + 'px';
});
}
}
win.DrawDewchart = DrawDewchart;
})(window, document);
css代碼
.chart-dew {
width: 90%;
height: 230px;
margin: 0 auto;
border: 1px solid #ccc;
}
.chart-dew .content-body {
width: 100%;
overflow-x: auto;
}
.chart-dew .chead {
height: 30px;
text-align: right;
background: #ccc;
padding: 5px;
color: #b72012;
}
.chart-dew .cbody {
min-width: 100%;
height: 198px;
overflow-y: hidden;
overflow-x: auto;
}
.chart-dew .cbody div {
float: left;
width: 30px;
height: 100%;
border-right: 1px solid #ccc;
text-align: center;
}
.chart-dew .cbody span {
display: block;
font-size: 14px;
border: 1px solid #0062CC;
border-radius: 50%;
height: 22px;
width: 22px;
text-align: center;
margin: 2px auto 0;
}
.chart-dew .cbody div:nth-child(even) {
display: inline-block;
background: #efeff4;
}
.chart-dew .red {
border: 1px solid red !important;
}
調用
html內容
<div class="chart-dew" id="test"></div>
js調用
var a = new DrawDewchart({
container: "#test12",
data: ['小', '小', '小', '小', '小', '小', '小', '小', '大', '大', '大', '小', '小', '小', '小', '大', '大', '小', '小'],
label: ['大', '小'],
red: '大',
title: '大小露珠圖'
});