JavaScript封装大全

2023-06-14,,

JavaScript封装大全-持续更新

Ajax封装

// 使用该封装需注意
// Ajax(method(默认GET), url(网址 必传), success(res){(成功时数据处理函数 必传)}, error(res)(失败时数据处理函数), data(网址中qurey部分 用对象形式存储 默认为空)) // 使用ES6语法
class Ajax {
// 解构传入的值 默认参数为空
constructor({method='GET', url, success, error, data={}}={}) {
this.method = method;
this.url = url;
this.success = success;
this.error = error;
this.data = data;
this.main();
}
main() {
const that = this;
// 如果没传入success 则为false return结束程序
if (!this.success) {
console.log('缺少必传参数success');
return;
}; // 如果没有传入url 则为false return结束程序
if (!this.url) {
console.log('缺少必传参数url');
return;
} // 创建xhr载体对象
const xhr = new XMLHttpRequest(); // 拼接data中键值对
let str = '';
for (let key in data) {
str += `${key}=${data[key]}&`;// key=value&key=value&
} if (this.method.toUpperCase() === 'GET') {
url += str.slice(0, -1);// key=value&key=value
} xhr.open(this.method, this.url);
if (this.method.toUpperCase() === 'GET') {
// GET数据格式默认为[querystring]
xhr.send(null);
} else {
// POST需要设置数据格式
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(str.slice(0, -1));
} xhr.onload = function() {
if (xhr.status === 200) {
// 将xhr响应交给success处理函数
that.success(xhr.response);
} else {
// 将错误xhr状态交给error处理函数
that.error && that.error(xhr.status);
}
}
}
}

Cookie封装

//  cookie语法字符
// 名字=值;配置名=配置信息;配置名=配置信息;
// - 配置名
// expires 有效期
// 值 必须为日期对象
// path 路径
// 值 为路径名 // 增
function setCookie(key, value, ops={}) {
// 从ops中找到path拼接 没有则为空字符串
const path = ops.path ? `;path=${ops.path}` : '';
const d = new Date();
// 从ops中找到expires和d相加并设置给d
d.setDate(d.getDate() + ops.expires)
// 将expires拼接 没有则为空字符串
const exp = ops.expires ? `;expires=${d}` : '';
//将所有字符串拼接成有效cookie字符
document.cookie = `${key}=${value}${exp}${path}`;
} // 删
function deleteCookie(key, ops={}) {
// 将ops中的expires修改为负值 即为删除cookie
ops.expires = -1;
// 利用setCookie将修改expires值给到key对应cookie
setCookie(key, '', ops);
} // 查
function getCookie(key) {
// 通过document.cookie获取到当前所有cookie组成的一个字符串 并使用splice分割成数组
const arr = document.cookie.split('; ')
// 循环数组
for (let i = 0; i < arr.length; i++) {
// 用splice分割字符串 并找到对应key值
if (arr[i].split('=')[0] === key) {
// 返回对应key值的value
return arr[i].split('=')[1];
}
}
// 如果document.cookie中不存在 返回null
return null;
}

缓速动画封装

// slowMotion(需要运动元素, data中存放left和top键值对表示要运动到目标位置, 回调函数)
function slowMotion(element, data, callback) {
// 函数节流 配合下面的element.timer = null;
if (element.timer) return; // 函数防抖 不需要配合element.timer = null; 有小
// clearInterval(element.timer); element.timer = setInterval(() => {
// 设置状态 用于记录是否到达目标位置
let flag = false;
// 循环
for (let attr in data) {
// 使用封装非行内属性的值找到当前位置
const now = getStyle(element, attr);
// 目标位置 - 当前位置 / 8 为步长 随着当前位置离目标位置越近 差值越小 步长越小 实现缓动
let step = (data[attr] - now) / 8;
// 步长取整
step = step < 0 ? Math.floor(step) : Math.ceil(step);
// 将当前位置 + 步长给到对应attr(left或者top)实现元素运动
element.style[attr] = now + step + 'px';
// 当元素到达终点时 将状态设置为true
if (now == data[attr]) flag = true;
} //状态为true 表示元素已到达终点
if (flag) {
// 清除间隔器
clearInterval(element.timer);
// 缺失这段代码 函数节流一直生效 无法开启下一个间隔器
element.timer = null;
// 调用传进来的回调函数 利用短路特性 当没有callback时 右边将不执行
// 可以利用回调函数调用slowMotion函数实现 当元素到达当前目标位置时 继续向下一个目标位置缓动...
// 例 slowMotion(div, {left : 100} () => {slowMotion(div, {top : 100})})
callback && callback();
}
}, 30)
} // 封装获取非行内属性的值(浏览器兼容) element为对应元素 attribute为非行内属性
function getStyle(element, attribute) {
return element.currentStyle ? element.currentStyle[attribute] : getCpmputed(element)[attribute];
}

元素基础拖拽封装

// new Drag(传入需拖拽的元素);
class Drag {
constructor (element) {
this.element = element;
this.addEvent();
} addEvent() {
// 原来downMouse内部的this指向element 这里将this指向强行修改指向Drag创建出来的实例对象
// 用 bind 原因是bind不会自动执行函数
this.element.onmousedown = this.downMouse.bind(this);
} downMouse(event) {
// element的事件对象(浏览器兼容)
this.downE = event || window.event;
// 原来moveMouse和removeMouse内部的this指向document 这里将this指向强行修改指向downMouse内部this指向 因为downMouse内部指向已经从element修改为Drag实例对象 所以moveMouse和removeMouse内部的this也指向Drag实例对象
// 用 bind 原因是bind不会自动执行函数
document.onmousemove = this.moveMouse.bind(this);
document.onmouseup = this.removeMouse.bind(this);
} moveMouse(event) {
// document的事件对象(浏览器兼容)
this.moveE = event || window.event;
// 将鼠标在页面中的位置 - 鼠标相对于元素的偏移量得到元素左/上边应该距离页面的位置
let l = this.moveE.pageX - this.downE.offsetX;
let t = this.moveE.pageY - this.downE.offsetY;
// 将元素限制在可视区域内(边界限定)
// 这里if条件里不用 = 的原因是 如果用 = 当拖拽元素到边界上时会吸附在边界上
if (l < 0) l = 0;
if (t < 0) t = 0;
// document.documentElement.clientWidth/Height为当前可视区域大小
// this.element.offsetWidth/Height为当前元素宽高
if (l > document.documentElement.clientWidth - this.element.offsetWidth) l = document.documentElement.clientWidth - this.element.offsetWidth;
if (t > document.documentElement.clientHeight - this.element.offsetHeight) t = document.documentElement.clientHeight - this.element.offsetHeight;
// 把当前位置给到元素的left/top
this.element.style.left = l + 'px';
this.element.style.top = t + 'px';
} removeMouse() {
// 鼠标抬起后 删除鼠标移动和抬起事件
document.onmousemove = null;
document.onmouseup = null;
}
}

JavaScript封装大全的相关教程结束。

《JavaScript封装大全.doc》

下载本文的Word格式文档,以方便收藏与打印。