dataset兼容低版本IE的方法

元素dataset属性兼容性很差,IE11以上才支持,所以写了个方法兼容下,下面是代码

function getDataset(ele){
    if(ele.dataset){
        return ele.dataset;
    }else{
        var attrs = ele.attributes,//元素的属性集合
            dataset = {},
            name,
            matchStr;

        for(var i = 0;i<attrs.length;i++){
            //是否是data- 开头
            matchStr = attrs[i].name.match(/^data-(.+)/);
            if(matchStr){
                //data-auto-play 转成驼峰写法 autoPlay
                name = matchStr[1].replace(/-([\da-z])/gi,function(all,letter){
                    return letter.toUpperCase();
                });
                dataset[name] = attrs[i].value;
            }
        }
        return dataset;
    }
}
发布了25 篇原创文章 · 获赞 31 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_33236453/article/details/78599297