(function(window, $) { 'use strict'; function WordBox(wrapper, options) { var defaults = { isLead: false, // 是否包含“全部”分类,该lead分类会始终显示在第一个位置上 leadWord: null, words: null, colors: ['#cc5b34', '#c27c4d'], isFixedWidth: true, width: 1000, height: 200 }; this.options = $.extend(false, defaults, options); this.$wrapper = $(wrapper); if (!this.$wrapper || this.options.words.length < 1) { return false; } this._create(); this._bindListener(); return this; }; WordBox.prototype = { words: [], colors: [], colorPos: 0, _create: function() { if (this.options.isLead && this.options.leadWord) { this.words = [this.options.leadWord].concat(this._randArray(this.options.words)); } else { this.words = this._randArray(this.options.words); } //容器宽高初始化 if (this.options.isFixedWidth) { this.$wrapper.width(this.options.width); this.$wrapper.height(this.options.height); } else { // 容器宽高根据父级元素自适应 this.$wrapper.width(this.$wrapper.parent().width()); this.$wrapper.height(this.$wrapper.parent().height()); } this.fillRect(this.$wrapper, 0, 0, this.$wrapper.width(), this.$wrapper.height(), this.words); }, /* * 递归创建box */ fillRect: function(wrapper, left, top, width, height, words) { var wordLen = words.length, ratio = width / height, dot = this._randRange(1, 2, 0.5), wordLen1 = Math.round(wordLen * dot[0]), wordLen2 = wordLen - wordLen1; if (wordLen == 1) { this._createBox(wrapper, left, top, width, height, words[0], this._getNextColor()); return; } if (wordLen1 == 0) { wordLen1 = 1; wordLen2--; } else if (wordLen2 == 0) { wordLen2 = 1; wordLen1--; } if (ratio >= 2.5) { // 左右分割 var leftW = Math.round(width * dot[0]), rightW = width - leftW; this.fillRect(wrapper, left, top, leftW, height, words.slice(0, wordLen1)); this.fillRect(wrapper, left+leftW, top, rightW, height, words.slice(wordLen1)); } else { // 上下分割 var topH = Math.round(height * dot[0]), bottomH = height - topH; this.fillRect(wrapper, left, top, width, topH, words.slice(0, wordLen1)); this.fillRect(wrapper, left, top+topH, width, height-topH, words.slice(wordLen1)); } }, /* * 创建box * @param left、right为box相对于 wrapper 绝对定位的偏移量 */ _createBox: function(wrapper, left, top, width, height, word, color) { var lineHeight = height, paddingTop = 0, wordW = this._getWordsWidth(word.title); // 如果box中文字的宽度超出box本身的宽度,则需要分多行显示 if (wordW > width) { var line = Math.ceil(wordW / width); // 注意设置 line-height 属性和 padding-top 属性 lineHeight = parseInt(this.$wrapper.css('font-size')); paddingTop = Math.max(0, (height - line * lineHeight) / 2); height -= paddingTop; } var html = '