export default class Utils {
static IMG_LOAD_FINISH = "img_load_finish";
constructor() {
}
static ce(type, style, data, prop) {
let elem = document.createElement(type);
if (style) Object.assign(elem.style, style);
if (data) Object.assign(elem, data);
if (prop){
for(let str in prop){
elem.setAttribute(str,prop[str]);
}
}
return elem;
}
static randomColor() {
let c = "#";
for (let i = 0; i < 6; i++) {
c += Math.floor(Math.random() * 16).toString(16);
}
return c;
}
static random(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
static loadImgs(imgList, baseUrl, handler, type) {
let img = new Image();
img.addEventListener("load", Utils.loadHandler);
let url = Utils.getImgUrl(imgList[0], baseUrl, type);
img.src = url;
img.imgList = imgList;
img.baseUrl = baseUrl;
img.handler = handler;
img.type = type;
img.list = [];
img.num = 0;
}
static loadHandler(e) {
let img = this.cloneNode(false);
this.list.push(img);
this.num++;
if (this.num > this.imgList.length - 1) {
this.removeEventListener("load", Utils.loadHandler);
if (this.handler) {
this.handler(this.list);
return;
}
let evt = new Event(Utils.IMG_LOAD_FINISH);
evt.list = this.list;
document.dispatchEvent(evt);
return;
}
this.src = Utils.getImgUrl(this.imgList[this.num],
this.baseUrl, this.type);
}
static getImgUrl(name, baseUrl, type) {
let url = "";
if (baseUrl) url += baseUrl;
if (type) {
if (name.indexOf(".") < 0) name += "." + type;
else name = name.replace(/\.\w+$/, "." + type);
}
url += name;
return url
}
}
1、ce方法,创建DOM方法,可以给DOM添加样式对象,对象属性,标签属性
Utils.ce("div",{
width:"50px",
height:"50px",
backgroundColor:"red"
},{
textContent:"hello",
a:2
},{
class:"div0 div1",
title:"div"
});
2、randomColor获取随机色
let color=Utils.randomColor();
3、random随机求最小值到最大值之间的整数
let num=Utils.random();
4、loadImgs预加载图片
Utils.loadImgs(图片名数组,基础地址,加载完成的回调函数,图片扩展名 )
例子1 只有文件名,扩展名可以统一修改
let arr=["a,"b","c","d","e"];
Utils.loadImgs(arr,"./img/",loadFinish,"png");
//这里相当于加载了,./img/a.png,./img/b.png,./img/c.png,./img/d.png,
./img/e.png
function loadFinish(list){
console.log(list);
//list加载完成的图片数组
}
例子2 可以不同扩展名
let arr=["a.png,"b.jpg","c.png","d.jpg","e.png"];
Utils.loadImgs(arr,"./img/",loadFinish);
//这里相当于加载了,./img/a.png,./img/b.jpg,./img/c.png,./img/d.jpg,
./img/e.png
function loadFinish(list){
console.log(list);
//list加载完成的图片数组
}
例子3 可以不同路径
let arr=["./img/a.png,"./img/b.jpg","./img/c.png",
"./imgs/d.jpg","./imgs/e.png"];
Utils.loadImgs(arr,null,loadFinish);
//这里相当于加载了,./img/a.png,./img/b.jpg,./img/c.png,./imgs/d.jpg,
./imgs/e.png
function loadFinish(list){
console.log(list);
//list加载完成的图片数组
}
例子4 可以使用事件侦听,不使用回调函数,这样可以在任意位置获取
let arr=["a.png,"b.jpg","c.png","d.jpg","e.png"];
document.addEventListener(Utils.IMG_LOAD_FINISH,loadFinish)
Utils.loadImgs(arr,"./img/");
//这里相当于加载了,./img/a.png,./img/b.jpg,./img/c.png,./img/d.jpg,
./img/e.png
function loadFinish(e){
console.log(e.list);
//e.list加载完成的图片数组
}