//參數(shù)選擇器名稱,返回值:dom對象
function getClass(className) // 類的寫法
{
//判斷支持否
if (document.getElementsByClassName) {
return document.getElementsByClassName(className);
}
var arr = [];
var dom = document.getElementsByTagName("*");
for (var i = 0; i < dom.length; i++) {
var txtarr = dom[i].className.split(" ");
for (var j = 0; j < txtarr.length; j++) {
if (txtarr[j] == className) {
arr.push(dom[i]);
}
}
}
return arr;
}
function $(str) {
var tag = str.charAt(0);
var id = str.substr(1); // demo
switch (tag) {
case "#":
return document.getElementById(id);
case ".":
return getClass(id);
default:
return document.getElementsByTagName(str);
}
}
//返回值:left,top
function scroll() {
//IE9+ 和其他瀏覽器
if (window.pageYOffset != null) {
return {
left: window.pageXOffset,
top: window.pageYOffset
}
}
//不是怪異模式 有DTD的
else if (document.compatMode == "CSS1Compat") {
return {
left: document.documentElement.scrollLeft,
top: document.documentElement.scrollTop
}
}
//谷歌瀏覽器和怪異模式
return {
left: document.body.scrollLeft,
top: document.body.scrollTop
}
}
//參數(shù):dom對象,目標(biāo)位置
function animate(obj, target) {
clearInterval(obj.timer); // 先清除定時器
var speed = obj.offsetLeft < target ? 10 : -10; // 用來判斷 應(yīng)該 + 還是 -
obj.timer = setInterval(function () {
var result = target - obj.offsetLeft; // 因為他們的差值不會超過5
obj.style.left = obj.offsetLeft + speed + "px";
if (Math.abs(result) <= 5) // 如果差值不小于 5 說明到位置了
{
clearInterval(obj.timer);
obj.style.left = target + "px"; // 有5像素差距 我們直接跳轉(zhuǎn)目標(biāo)位置
}
}, 10)
}
//返回值width,height
function client() {
if (window.innerWidth != null) // ie9 + 最新瀏覽器
{
return {
width: window.innerWidth,
height: window.innerHeight
}
}
else if (document.compatMode === "CSS1Compat") // 標(biāo)準瀏覽器
{
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight
}
}
return { // 怪異瀏覽器
width: document.body.clientWidth,
height: document.body.clientHeight
}
}
function animate2(obj, target) {
clearInterval(obj.timer)
obj.timer = setInterval(function () {
var step = (target - obj.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
obj.style.left = obj.offsetLeft + step + "px";
if (obj.offsetLeft === target) {
clearInterval(obj.timer)
}
}, 10)
}
function getStyle(obj, attr) {
if (obj.currentStyle) {
return obj.currentStyle[attr];
} else {
return window.getComputedStyle(obj, null)[attr];
}
}
function animate3(obj, json, fn) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var flag = true;
for (var attr in json) {
var current = parseInt(getStyle(obj, attr));
var step = (json[attr] - current) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if (attr == "opacity") {
if ("opacity" in obj.style) {
obj.style.opacity = json[attr];
} else {
obj.style.filter = "alpha(opacity=" + json[attr] * 100 + ")";
}
} else {
obj.style[attr] = current + step + "px";
}
if (current != json[attr]) {
flag = false;
}
}
if (flag) {
clearInterval(obj.timer);
if (fn) {
fn();
}
}
}, 10)
}