文章出處

接到個新需求,類似以下這種需求,得把它封裝成一個插件

后端給返回一個這種數據

var data = [
    {
        key:"020506",
        num:5
    },
    {
        key:"03",
        num:2
    }
];
key:

02:表示第一層,0205:表示第二層,020506:第三層

如果第三層有新消息,則它本身和它上面的層級都需要顯示提示,并顯示數量,另外,后端將需要添加提示的元素,都加上了data-newinfo屬性,里面的值是它當前的層級。

num:

消息提示的數量

一些注意點
var newinfo = document.createElement('newinfo');

原本想創建一個span元素,但想想還是不太行,因為對應的那個頁面很有可能設置了span的樣式,而我們是不希望這樣的,因此創建了一個特別的元素。

/*          
使用說明:

data:數據
setInfo():將消息提示添加到頁面中

new NewInfo(data).setInfo();
------------------------------------
<div data-newinfo="020505"></div>
var data = [
    {
        key:"020506",
        num:5
    },
    {
        key:"03",
        num:2
    }
];
*/
function NewInfo(data){
    this.data = data;
    // 獲取所有需要添加新消息提示的元素
    this.newinfoDoms = Array.prototype.slice.call(document.querySelectorAll("[data-newinfo]"));
    // 樣式
    this.sty = "padding: 2px 5px;background-color: red;border-radius: 100%;color: #fff;font-size: 12px;vertical-align: 4px;line-height:1;";
}
NewInfo.prototype = {
    // 獲取所需的信息
    getInfo:function(){
        var _this = this;
        var arr = [];
        this.newinfoDoms.forEach(function(item,index){
            var isTrue = true;
            _this.data.forEach(function(item2,index){
                var isNewInfo = item2.key.substring(0,item.dataset.newinfo.length)===item.dataset.newinfo;
                if(isNewInfo&&item.dataset.newinfo){
                    if(isTrue){
                        arr.push({
                            'item':item,
                            'num':item2.num
                        });
                    }else{
                        arr[arr.length-1].num += item2.num;
                    }
                    isTrue = false;
                }
            });
        });
        return arr;
    },
    // 添加到相應的頁面中
    setInfo:function(){
        var _this = this;
        var arr = this.getInfo();
        arr.forEach(function(current,index){
            var newinfo = document.createElement('newinfo');
            newinfo.style.cssText = _this.sty;
            if(current.num>0){
                newinfo.innerHTML = current.num;
            }else{
                newinfo.style.paddingTop = '0';
                newinfo.style.paddingBottom = '0';
            }
            current.item.appendChild(newinfo);
        })
    }
};

效果


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()