Welcome to [Hexo]
JS封装方法总结
求滚动条滚动距离
function getScrollOffset() {
if (window.pageXOffset) {
return {
x: window.pageXOffset,
y: window.pageYOffset
}
} else {
return {
x: document.body.scrollLeft + document.documentElement.scrollLeft,
y: document.body.scrollTop + document.documentElement.scrollTop
}
}
}
返回浏览器视口尺寸
function getViewportOffset() {
if (window.innerWidth) {
return {
w: window.innerWidth,
h: window.innerHeight
}
} else {
if (document.compatMode === "BackCompat") {
return {
w: document.body.clientWidth,
h: document.body.clientHeight
}
} else {
return {
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight
}
}
}
}
获取元素样式(兼容)
function getStyle(elem, prop) {
if (window.getComputedStyle) {
return window.getComputedStyle(elem, null)[prop];
} else {
return elem.currentStyle[prop];
}
}
给一个dom对象添加该事件类型的函数(兼容)
function addEvent(elem, type, handle) {
if (elem.addEventListener) {
elem.addEventListener(type, handle, false);
} else if (elem.attachEvent) {
elem.attachEvent('on' + type, function () {
handle.call(elem);
})
} else {
elem['on' + type] = handle;
}
}
删除事件
function removeEvent(elem, type, handle) {
if (typeof elem.removeEventListener !== 'undefined') {
elem.removeEventListener(type, handle, false);
} else if (typeof elem.detachEvent !== 'undefined') {
elem.detachEvent('on' + type);
}
}
取消冒泡(兼容)
function stopBubble(event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
阻止默认事件函数
function cancelHandler(event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
拖拽事件
function drag(elem) {
var disX,
disY;
addEvent(elem, 'mousedown', function (e) {
var event = e || window.event;
disX = event.clientX - parseInt(getStyle(elem, 'left'));
disY = event.clientY - parseInt(getStyle(elem, 'top'));
addEvent(document, 'mousemove', mouseMove);
addEvent(document, 'mouseup', mouseUp);
stopBubble(event);
cancelHandler(event);
});
function mouseMove(e) {
var event = e || window.event;
elem.style.left = event.clientX - disX + "px";
elem.style.top = event.clientY - disY + "px";
}
function mouseUp(e) {
var event = e || window.event;
removeEvent(document, 'mousemove', mouseMove);
removeEvent(document, 'mouseup', mouseUp);
}
}
异步加载(兼容)
function loadScript(url, callback) {
var script = document.createElement('script');
script.type = "text/javascript";
if (script.readyState) {
script.onreadstatechange = function () {//IE
if (script.readyState == "complete" || script.readyStatereadyState == "loaded") {
callback();
}
}
} else {
script.onload = function () {
callback();
}
}
script.src = url;
document.head.appendChild(script);
}
loadScript('/*路径*/', function () {
test();
})
获取指定标签对象
/**
* 获取指定标签对象
* @param id 标签的id属性值
* @returns {Element}根据id属性值返回指定标签对象
*/
function my$(id) {
return document.getElementById(id);
}
设置任意的标签中间的任意文本内容
function setInnerText(element, text) {
//判断浏览器是否支持这个属性
if (typeof element.textContent == "undefined") {//不支持
element.innerText = text;
} else {//支持这个属性
element.textContent = text;
}
}
my$("btn").onclick = function () {
console.log(getInnerText(my$("dv")));
};
获取任意标签中间的文本内容
function getInnerText(element) {
if (typeof element.textContent == "undefined") {
return element.innerText;
} else {
return element.textContent;
}
}
my$("btn").onclick = function () {
setInnerText(my$("dv"), "哈哈,我又变帅了");
};
获取任意一个父级元素的第一个子级元素
function getFirstElementChild(element) {
if (element.firstElementChild) {//true--->支持
return element.firstElementChild;
} else {
var node = element.firstChild;//第一个节点
while (node && node.nodeType != 1) {
node = node.nextSibling;
}
return node;
}
}
console.log(getFirstElementChild(my$("uu")).innerText);
获取任意一个父级元素的最后一个子级元素
function getLastElementChild(element) {
if (element.lastElementChild) {//true--->支持
return element.lastElementChild;
} else {
var node = element.lastChild;//第一个节点
while (node && node.nodeType != 1) {
node = node.previousSibling;
}
return node;
}
}
console.log(getLastElementChild(my$("uu")).innerText);
获取某个元素的前一个兄弟元素
/**
* 获取某个元素的前一个兄弟元素
* @param element 某个元素
* @returns {*} 前一个兄弟元素
*/
function getPreviousElement(element) {
if (element.previousElementSibling) {
return element.previousElementSibling
} else {
var node = element.previousSibling;
while (node && node.nodeType != 1) {
node = node.previousSibling;
}
return node;
}
}
获取某个元素的后一个兄弟元素
/**
* 获取某个元素的后一个兄弟元素
* @param element 某个元素
* @returns {*} 后一个兄弟元素
*/
function getNextElement(element) {
if (element.nextElementSibling) {
return element.nextElementSibling
} else {
var node = element.nextSibling;
while (node && node.nodeType != 1) {
node = node.nextSibling;
}
return node;
}
}
获取某个元素的所有兄弟元素
/**
* 获取某个元素的所有兄弟元素
* @param element 某个元素
* @returns {Array} 兄弟元素
*/
function getSiblings(element) {
if (!element) return;
var elements = [];
var ele = element.previousSibling;
while (ele) {
if (ele.nodeType === 1) {
elements.push(ele);
}
ele = ele.previousSibling;
}
ele = element.nextSibling;
while (ele) {
if (ele.nodeType === 1) {
elements.push(ele);
}
ele = ele.nextSibling;
}
return elements;
}
为任意元素.绑定任意的事件, 任意的元素,事件的类型,事件处理函数
function addEventListener(element, type, fn) {
//判断浏览器是否支持这个方法
if (element.addEventListener) {
element.addEventListener(type, fn, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, fn);
} else {
element["on" + type] = fn;
}
}
为任意的一个元素,解绑对应的事件
function removeEventListener(element, type, fnName) {
if (element.removeEventListener) {
element.removeEventListener(type, fnName, false);
} else if (element.detachEvent) {
element.detachEvent("on" + type, fnName);
} else {
element["on" + type] = null;
}
}
格式化日期
/**
* 格式化日期
* @param dt 日期对象
* @returns {string} 返回值是格式化的字符串日期
*/
function getDates(dt) {
var str = "";//存储时间的字符串
//获取年
var year = dt.getFullYear();
//获取月
var month = dt.getMonth() + 1;
//获取日
var day = dt.getDate();
//获取小时
var hour = dt.getHours();
//获取分钟
var min = dt.getMinutes();
//获取秒
var sec = dt.getSeconds();
month = month < 10 ? "0" + month : month;
day = day < 10 ? "0" + day : day;
hour = hour < 10 ? "0" + hour : hour;
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
str = year + "年" + month + "月" + day + "日 " + hour + ":" + min + ":" + sec;
return str;
}
返回当前浏览器是什么类型的浏览器
function userBrowser() {
var browserName = navigator.userAgent.toLowerCase();
if (/msie/i.test(browserName) && !/opera/.test(browserName)) {
console.log("IE");
} else if (/firefox/i.test(browserName)) {
console.log("Firefox");
} else if (/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName)) {
console.log("Chrome");
} else if (/opera/i.test(browserName)) {
console.log("Opera");
} else if (/webkit/i.test(browserName) && !(/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName))) {
console.log("Safari");
} else {
console.log("不知道什么鬼!");
}
}
动画函数—任意一个元素移动到指定的目标位置
function animate(element, target) {
//先清理定时器
clearInterval(element.timeId);
//一会要清理定时器(只产生一个定时器)
element.timeId = setInterval(function () {
//获取div的当前的位置
var current = element.offsetLeft;//数字类型,没有px
//div每次移动多少像素---步数
var step = 10;
step = current < target ? step : -step;
//每次移动后的距离
current += step;
//判断当前移动后的位置是否到达目标位置
if (Math.abs(target - current) > Math.abs(step)) {
element.style.left = current + "px";
} else {
//清理定时器
clearInterval(element.timeId);
element.style.left = target + "px";
}
}, 20);
}
my$("btn2").onclick = function () {
animate(my$("dv"), 800);
};
变速动画-任意一个元素移动到指定的目标位置
function animateChange(element, target) {
//清理定时器
clearInterval(element.timeId);
element.timeId = setInterval(function () {
//获取元素的当前位置
var current = element.offsetLeft;
//移动的步数
var step = (target-current)/10;
step = step>0?Math.ceil(step):Math.floor(step);
current += step;
element.style.left = current + "px";
if(current==target) {
//清理定时器
clearInterval(element.timeId);
}
//测试代码:
console.log("目标位置:"+target+",当前位置:"+current+",每次移动步数:"+step);
}, 20);
}
my$("btn2").onclick = function () {
animateChange(my$("dv"), 800);
};
foreach的兼容代码
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(' this is null or not defined');
}
// 1. Let O be the result of calling toObject() passing the
// |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get() internal
// method of O with the argument "length".
// 3. Let len be toUint32(lenValue).
var len = O.length >>> 0;
// 4. If isCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== "function") {
throw new TypeError(callback + ' is not a function');
}
// 5. If thisArg was supplied, let T be thisArg; else let
// T be undefined.
if (arguments.length > 1) {
T = thisArg;
}
// 6. Let k be 0
k = 0;
// 7. Repeat, while k < len
while (k < len) {
var kValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty
// internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k];
// ii. Call the Call internal method of callback with T as
// the this value and argument list containing kValue, k, and O.
callback.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
}