for DOM

github: https://github.com/laixiangran/commonJS/blob/master/src/forDOM.js

代码

/**
* Created by laixiangran on 2016/1/24
* homepage:http://www.cnblogs.com/laixiangran/
* for DOM
*/ (function(undefined) { var com = window.COM = window.COM || {}; com.$D = {
// 根据id查找
byId: function(id, context) {
var ctx = context || document;
return ctx.getElementById(id);
}, // 根据类名查找
byClassName: function(className, context) {
var ctx = context || document;
return ctx.getElementsByClassName(className);
}, // 根据标签名查找
byTagName: function(tagName, context) {
var ctx = context || document;
return ctx.getElementsByTagName(tagName);
}, // 在文档中添加样式
addSheet: function() {
var doc, cssCode;
if (arguments.length == 1) {
doc = document;
cssCode = arguments[0];
}else if (arguments.length == 2) {
doc = arguments[0];
cssCode = arguments[1];
}else {
alert("addSheet函数最多接受两个参数!");
}
var headElement = doc.getElementsByTagName("head")[0];
var styleElements = headElement.getElementsByTagName("style");
if(styleElements.length == 0){ // 如果不存在style元素则创建
if (!+"\v1") { // ie
doc.createStyleSheet();
}else {
var tempStyleElement = doc.createElement("style"); //w3c
tempStyleElement.setAttribute("type", "text/css");
headElement.appendChild(tempStyleElement);
}
}
var styleElement = styleElements[0];
var media = styleElement.getAttribute("media");
if (media != null && !/screen/.test(media.toLowerCase())) {
styleElement.setAttribute("media", "screen");
}
if (!+"\v1") { // ie
styleElement.styleSheet.cssText += cssCode;
}else if (/a/[-1] == "a") {
styleElement.innerHTML += cssCode; // 火狐支持直接innerHTML添加样式表字串
}else{
styleElement.appendChild(doc.createTextNode(cssCode))
}
}, /*
* iframe高度自适应
* @param id iframe的id
* @param endTime 计算的时间
* */
adjustIframe: function(id, endTime) {
var iframe = this.byId(id),
time = 0,
end = endTime || 30,
intervalID;
if (iframe) {
function callback() {
time = time + 1;
if (time == end) {
clearInterval(intervalID)
}
var idoc = iframe.contentWindow && iframe.contentWindow.document || iframe.contentDocument;
var iheight = Math.max(idoc.body.scrollHeight, idoc.documentElement.scrollHeight);
iframe.style.height = iheight + "px";
}
intervalID = setInterval(callback, 50)
}
}, /*
* 拖拽元素
* @param elem 拖拽的元素
* @param callback 拖拽结束之后的回调函数
* */
drag: function(elem, callback) {
callback = callback || function() {};
var $D = this;
var params = {
left: 0,
top: 0,
currentX: 0,
currentY: 0,
flag: false
};
if ($D.getStyle(elem, "left") !== "auto") {
params.left = $D.getStyle(elem, "left");
}
if ($D.getStyle(elem, "top") !== "auto") {
params.top = $D.getStyle(elem, "top");
}
elem.onmousedown = function(event) {
params.flag = true;
event = event || window.event;
params.currentX = event.clientX;
params.currentY = event.clientY;
};
document.onmousemove = function(event) {
event = event || window.event;
if (params.flag) {
var nowX = event.clientX,
nowY = event.clientY;
var disX = nowX - params.currentX,
disY = nowY - params.currentY;
elem.style.left = parseInt(params.left) + disX + "px";
elem.style.top = parseInt(params.top) + disY + "px";
}
};
document.onmouseup = function() {
params.flag = false;
if ($D.getStyle(elem, "left") !== "auto") {
params.left = $D.getStyle(elem, "left");
}
if ($D.getStyle(elem, "top") !== "auto") {
params.top = $D.getStyle(elem, "top");
}
callback(elem);
};
}, // 获取元素被窗口卷去的上部分高度
getScrollTop: function(elem) {
var doc = elem ? elem.ownerDocument : document;
return doc.documentElement.scrollTop || doc.body.scrollTop;
}, // 获取元素被窗口卷去的左部分宽度
getScrollLeft: function(elem) {
var doc = elem ? elem.ownerDocument : document;
return doc.documentElement.scrollLeft || doc.body.scrollLeft;
}, // 获取元素的左偏移量
getElementLeft: function(elem) {
var actualLeft = elem.offsetLeft;
var current = elem.offsetParent;
while (current !== null) {
actualLeft += current.offsetLeft;
current = current.offsetParent;
}
return actualLeft;
}, // 获取元素的上偏移量
getElementTop: function(elem) {
var actualTop = elem.offsetTop;
var current = elem.offsetParent;
while (current !== null) {
actualTop += current. offsetTop;
current = current.offsetParent;
}
return actualTop;
}, // 获取元素的范围(包括窗口不可见的部分)
rect: function(elem) {
var left = 0,
top = 0,
right = 0,
bottom = 0;
if (!elem.getBoundingClientRect) {
left = this.getElementLeft(elem);
top = this.getElementTop(elem);
right = left + elem.offsetWidth;
bottom = top + elem.offsetHeight;
} else {
var rect = elem.getBoundingClientRect();
left = right = this.getScrollLeft(elem);
top = bottom = this.getScrollTop(elem);
left += rect.left;
right += rect.right;
top += rect.top;
bottom += rect.bottom;
}
return {
"left": left,
"top": top,
"right": right,
"bottom": bottom
};
}, // 获取元素在窗口可见的范围
clientRect: function(elem) {
var rect = this.rect(elem),
sLeft = this.getScrollLeft(elem),
sTop = this.getScrollTop(elem);
rect.left -= sLeft;
rect.right -= sLeft;
rect.top -= sTop;
rect.bottom -= sTop;
return rect;
}, // 获取浏览器视口大小
getViewport: function() {
if (document.compatMode == "BackCompat") { // 判断是否运行在混杂模式
return {
"width": document.body.clientWidth,
"height": document.body.clientHeight
};
} else {
return {
"width": document.documentElement.clientWidth,
"height": document.documentElement.clientHeight
};
}
}, /*
* 元素是否包含某元素
* @parma elemA 包含元素
* @param elemB 被包含元素
* */
contains: function(elemA, elemB) {
if (typeof elemA.contains == "function" && (!COM.$B.engine.webkit || COM.$B.engine.webkit >= 522)) {
return elemA.contains(elemB);
} else if (typeof elemA.compareDocumentPosition == "function") {
return !!(elemA.compareDocumentPosition(elemB) & 16);
} else {
var node = elemB.parentNode;
do {
if (node === elemA) {
return true;
} else {
node = node.parentNode;
}
} while (node !== null);
return false;
}
}, // 获取所有css属性
curStyle: function(elem) {
if (document.defaultView && typeof document.defaultView.getComputedStyle == "function") {
return document.defaultView.getComputedStyle(elem, null);
} else {
return elem.currentStyle;
}
}, /*
* 获取元素指定的css属性的值
* @param elem 当前元素
* @parma name css属性名
* */
getStyle: function(elem, name) {
var style = null;
if (document.defaultView && typeof document.defaultView.getComputedStyle == "function") {
style = document.defaultView.getComputedStyle(elem, null);
return name in style ? style[name] : style.getPropertyValue(name);
} else {
var curStyle = elem.currentStyle;
style = elem.style; if (name == "opacity") {
if (/alpha\(opacity=(.*)\)/i.test(curStyle.filter)) {
var opacity = parseFloat(RegExp.$1);
return opacity ? opacity / 100 : 0;
}
return 1;
}
if (name == "float") {
name = "styleFloat";
}
var ret = curStyle[name] || curStyle[com.$S.camelize(name)]; // 单位转换
if (!/^-?\d+(?:px)?$/i.test(ret) && /^\-?\d/.test(ret)) {
var left = style.left,
rtStyle = elem.runtimeStyle,
rsLeft = rtStyle.left;
rtStyle.left = curStyle.left;
style.left = ret || 0;
ret = style.pixelLeft + "px";
style.left = left;
rtStyle.left = rsLeft;
}
return ret;
}
}, /*
* 设置元素指定的css属性的值
* @param elem 当前元素
* @parma style css属性名
* @param value css属性的指
* */
setStyle: function(elems, style, value) {
if (!elems.length) {
elems = [elems];
}
if (typeof style == "string") {
var s = style;
style = {};
style[s] = value;
}
com.$A.forEach(elems, function(elem) {
for (var name in style) {
if (style.hasOwnProperty(name)) {
var value = style[name];
if (name == "opacity" && com.$B.browser.ie) {
elem.style.filter = (elem.currentStyle && elem.currentStyle.filter || "").replace( /alpha\([^)]*\)/, "" ) + " alpha(opacity=" + (value * 100 | 0) + ")";
} else if (name == "float") {
elem.style[com.$B.browser.ie ? "styleFloat" : "cssFloat" ] = value;
} else {
elem.style[com.$S.camelize(name)] = value;
}
}
}
});
}, // 获取元素大小
getSize: function(elem) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
if (!width && !height) {
var repair = this.contains(document.body, elem),
parent;
if (!repair) { // 元素不在body上
parent = elem.parentNode;
document.body.insertBefore(elem, document.body.childNodes[0]);
}
var style = elem.style,
cssShow = {
position: "absolute",
visibility: "hidden",
display: "block",
left: "-9999px",
top: "-9999px"
},
cssBack = {
position: style.position,
visibility: style.visibility,
display: style.display,
left: style.left,
top: style.top
};
this.setStyle(elem, cssShow);
width = elem.offsetWidth;
height = elem.offsetHeight;
this.setStyle(elem, cssBack);
if (!repair) {
parent ? parent.appendChild(elem) : document.body.removeChild(elem);
}
}
return {
"width": width,
"height": height
};
}
};
}());

参考

http://www.cnblogs.com/cloudgamer/

commonJS — DOM操作(for DOM)的更多相关文章

  1. vue怎么不通过dom操作获取dom节点

    今天写一个公众号的项目,写了一个vue的搜索组件,点击搜索框时,背景出现一个遮罩,代码结构如下: template:`<div class="searchBar-div"&g ...

  2. 为什么DOM操作很慢

    转自:http://kb.cnblogs.com/page/534571/ 一直都听说DOM很慢,要尽量少的去操作DOM,于是就想进一步去探究下为什么大家都会这样说,在网上学习了一些资料,这边整理出来 ...

  3. DOM操作--表格点击行变色

    点击表格行变色,这种网页效果应该还是比较常见的.大家应该看见了,我这里的效果是用DOM操作实现的,那么很多人会问什么是DOM操作,贴出代码之前我就和大家解释一下什么是DOM操作: DOM是Docume ...

  4. jQuery2.x源码解析(DOM操作篇)

    jQuery2.x源码解析(构建篇) jQuery2.x源码解析(设计篇) jQuery2.x源码解析(回调篇) jQuery2.x源码解析(缓存篇) jQuery这个类库最为核心重要的功能就是DOM ...

  5. jQuery(3)——DOM操作

    ---恢复内容开始---   jQuery中的DOM操作 [DOM操作分类] DOM操作分为DOM Core(核心).HTML-DOM和CSS-DOM三个方面. DOM Core:任何一种支持DOM的 ...

  6. 第三章(jQuery中的DOM操作)

    3.1 DOM 操作分类 ①DOM Core 包括(getElementById() , getElementsByTagName() , getAttribute() , setAttribute( ...

  7. 为什么说DOM操作很慢

    转自http://www.cnblogs.com/yuzhongwusan/articles/5275933.html   一直都听说DOM很慢,要尽量少的去操作DOM,于是就想进一步去探究下为什么大 ...

  8. JavaScript的BOM、DOM操作、节点以及表格(二)

    BOM操作 一.什么是BOM BOM(Browser Object Model)即浏览器对象模型.     BOM提供了独立于内容 而与浏览器窗口进行交互的对象:     BOM由一系列相关的对象构成 ...

  9. 事件冒泡及事件委托的理解(JQuery Dom操作)

    jQuery事件冒泡: click mouseenter 等事件没有绑定 也会触发,只是触发后没有任何结果 子元素触发事件后,会把触发事件传递给父元素,那么父元素也会被触发. 不管有没有绑定事件,都会 ...

  10. BOM与DOM之DOM操作

    目录 一:DOM操作 1.DOM介绍 2.DOM标准规定HTML文档中的每个成分都是一个节点(node): 3.DOM操作需要用关键字 二:查找标签 1.id查找 类查找 标签查找(直接查找) 2.i ...

随机推荐

  1. HDU(4734),数位DP

    题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=4734 F(x) Time Limit: 1000/500 MS (Java/Others) ...

  2. linux文件描述符--转载

    转自:http://blog.csdn.net/cywosp/article/details/38965239 1. 概述     在Linux系统中一切皆可以看成是文件,文件又可分为:普通文件.目录 ...

  3. 在repeater增加自增长的序号

    <td><%#Container.ItemIndex+ %></td> 完!!!

  4. spring事务之——spring配置事务的五种方式

    Spring配置文件中关于事务配置总是由三个部分组成,分别是DataSource.TransactionManager和代理机制这三部分,无论哪种配置方式,一般变化的只是代理机制这部分. DataSo ...

  5. php5.3之前版本升级至5.3以及更高版本后部分语法简单归纳

    1. Deprecated: Assigning the return value of new by reference is deprecated in /usr/local/www/uugui/ ...

  6. C++函数前和函数后加const修饰符区别

    class Test(){ public: Test(){} const int foo(int a); const int foo(int a) const; }; 一.概念 当const在函数名前 ...

  7. How do I reset Windows Update components?

    https://support.microsoft.com/en-us/kb/971058 Download and run the Windows Update Troubleshooter for ...

  8. [Lonlife1031]Bob and Alice are eating food(递推,矩阵快速幂)

    题目链接:http://www.ifrog.cc/acm/problem/1031 题意:6个水果中挑出n个,使得其中2个水果个数必须是偶数,问有多少种选择方法. 设中0代表偶数,1代表奇数.分别代表 ...

  9. Java EE 锚、表格用法

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...

  10. Linux curl命令参数详解

    笔者出处:http://www.aiezu.com/system/linux/linux_curl_syntax.html linux curl是通过url语法在命令行下上传或下载文件的工具软件,它支 ...