Skip to content

Instantly share code, notes, and snippets.

@hjzheng
Created December 13, 2017 05:40
Show Gist options
  • Save hjzheng/77085c35f78f9eef18d70dff7b00603c to your computer and use it in GitHub Desktop.
Save hjzheng/77085c35f78f9eef18d70dff7b00603c to your computer and use it in GitHub Desktop.
DOM 操作与 YUI2 Dom的实现对比
1.Javascript中的String是没有trim方法,为String加上trim方法
//自定义函数
if (!String.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,'');
}
}
//YUI
2.YAHOO.lang.trim(s)
参数 字符串 , 返回值 字符串
替换掉 document.getElementById()
//自定义函数
function $(){
//存储返回元素的数组
var elements = new Array();
//arguments指的是$()函数的所有参数 对其进行遍历
for(var i=0;i<arguments.length;i++){
var element = arguments[i];
//如果参数是string类型,调用document.getElementById()方法
if(typeof element == 'string'){
element = document.getElementById(element);
}
//如果参数只用一个值,则直接返回
if(arguments.length == 1){
return element;
}
//如果参数多个 放入数组
elements.push(element);
}
//返回数组
return elements;
}
//YUI 2.8
YAHOO.util.Dom.get(e)
参数: 数组(id|HTML元素)|字符串(id)| HTML元素
返回值: HTML元素 | 数组(HTML元素)
3.为元素添加事件
//自定义函数
function addEvent(node,type,listener){
//参数node可以是字符串(id)或 HTML元素
//如果node不存在 添加事件失败
if(!(node = $(node))){return false;}
if(node.addEventListener){
//W3C 最后一个参数是否冒泡
node.addEventListener(type,listener,false);
return true;
}else if(node.attachEvent){
//MSIE
node['e'+type+listener] = listener;
node[type+listener] = function(){node['e'+type+listener]( window.event );}
node.attachEvent( 'on'+type, node[type+listener] );
return true;
}
//其他
return false
}
//YUI 2.8
YAHOO.util.Event.addListener ( el , sType , fn , obj , overrideContext )
参数 el <String|HTMLElement|Array|NodeList>
sType <String>
fn <Function>
obj <Object> An arbitrary object that will be passed as a parameter to the handler
overrideContext <Boolean|object> If true, the obj passed in becomes the execution context of the listener.
If an object, this object becomes the execution context.
返回值 boolean 是否成功
4.为元素取消事件
//自定义函数
function removeEvent(node, type, listener ) {
if(!(node = $(node))) return false;
if (node.removeEventListener) {
//W3C
node.removeEventListener( type, listener, false );
return true;
} else if (node.detachEvent) {
//MSIE
node.detachEvent( 'on'+type, node[type+listener] );
node[type+listener] = null;
return true;
}
//其他情况
return false;
};
//YUI 2.8
YAHOO.util.Event.removeListener ( el , sType , fn )
参数 el <String|HTMLElement|Array|NodeList>
sType <String>
fn <Function>
返回值 boolean 是否成功
4.getElementsByClassName()
//自定义函数
function getElementsByClassName(className, tag, parent){
parent = parent || document;
if(!(parent = $(parent))) return false;
// Locate all the matching tags
var allTags = (tag == "*" && parent.all) ? parent.all : parent.getElementsByTagName(tag);
var matchingElements = new Array();
// Create a regular expression to determine if the className is correct
className = className.replace(/\-/g, "\\-");
var regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
var element;
// Check each element
for(var i=0; i<allTags.length; i++){
element = allTags[i];
if(regex.test(element.className)){
matchingElements.push(element);
}
}
// Return any matching elements
return matchingElements;
};
//YUI
YAHOO.util.Dom.getElementsByClassName(className , tag , root , apply , o , overrides)
参数:
className <String>
tag <String> (可选)
root <String | HTMLElement> (可选)
apply <Function> (可选) A function to apply to each element when found
o <Any> (可选) An optional arg that is passed to the supplied method
overrides <Boolean> (可选) Whether or not to override the scope of "method" with "o"
返回值:Array
5.toggleDisplay(node,value)
//自定义函数
function toggleDisplay(node, value) {
if(!(node = $(node))) return false;
if ( node.style.display != 'none' ) {
node.style.display = 'none';
} else {
node.style.display = value || '';
}
return true;
}
//YUI 2.8
YUI 2.8中没有(我没有发现)
function toggleDisplay(node,value){
var Dom = YAHOO.util.Dom ;
if(!(node = Dom.get(node))) return false;
if( Dom.getStyle(node,"display") != 'none' ){
Dom.setStyle(node,"display",'none');
} else {
Dom.setStyle(node,"display",value || '');
}
}
function toggleClass(node,className){
var Dom = YAHOO.util.Dom ;
if(!(node = Dom.get(node))) return false;
if( Dom.hasClass(className)){
Dom.addClass(node,className);
}else{
Dom.removeClass(node,className);
}
}
6.对DOM的一些补充方法
DOM节点的属性
parentNode
childNodes
firstChild
lastChild
nextSibling
previousSibling
DOM中已有的方法
//获取节点
document.getElementById()
document.getElementsByTagName()
getAttribute() 获取属性
setAttribute()
//删除节点
removeChild()
removeAttribute()
//替换节点
replaceChild()
//创建节点
createElement()
//添加节点
appendChild()
insertBefore()
//clone 节点
cloneNode()
//自定义函数
/**
* 相对于insertBefore
*/
function insertAfter(node, referenceNode) {
if(!(node = $(node))) return false;
if(!(referenceNode = $(referenceNode))) return false;
return referenceNode.parentNode.insertBefore(node, referenceNode.nextSibling);
};
/**
* 删除所有的children 对比renoveChild
*/
function removeChildren(parent) {
if(!(parent = $(parent))) return false;
// While there is a child remove it
while (parent.firstChild) {
parent.firstChild.parentNode.removeChild(parent.firstChild);
}
// Return the parent again so you can stack the methods
return parent;
};
/**
* 相对于appendChild
*/
function prependChild(parent,newChild) {
if(!(parent = $(parent))) return false;
if(!(newChild = $(newChild))) return false;
if(parent.firstChild) {
// There is already a child so insert before the first one
parent.insertBefore(newChild,parent.firstChild);
} else {
// No children so just append
parent.appendChild(newChild);
}
// Return the parent again so you can stack the methods
return parent;
}
//YUI 2.8
YAHOO.util.Dom
//对节点操作的部分方法
getAttribute
getChildren
getFirstChild
getLastChild
getNextSibling
getPreviousSibling
insertAfter
insertBefore
setAttribute
getAttribute
7.获取浏览器窗口的大小 (Document可见区域的大小)
http://hi.baidu.com/hjzheng/blog/item/31494f61fc72e5cfe7113a8c.html
//自定义函数
function getBrowserWindowSize() {
var de = document.documentElement;
// window.innerWidth for most browsers
// document.documentElement.clientWidth for MSIE in strict mode
// document.body.clientWidth for MSIE in quirks mode
return {
'width':(
window.innerWidth
|| (de && de.clientWidth )
|| document.body.clientWidth),
'height':(
window.innerHeight
|| (de && de.clientHeight )
|| document.body.clientHeight)
}
};
//YUI 2.8
YAHOO.util.Dom.getViewportHeight()
YAHOO.util.Dom.getViewportWidth()
8.当document加载完成后,触发
//自定义函数
function addLoadEvent(loadEvent,waitForImages) {
// If the wait flag is true use the regular add event method
if(waitForImages) {
return addEvent(window, 'load', loadEvent);
}
// Otherwise use a number of different methods
// Wrap the loadEvent method to assign the correct content for the
// this keyword and ensure that the event doesn't execute twice
var init = function() {
if (arguments.callee.done) return;
// Return if this function has already been called
// Mark this function so you can verify if it was already run
arguments.callee.done = true;
// Run the load event in the context of the document
loadEvent.apply(document,arguments);
};
// Register the event using the DOMContentLoaded event
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
// For Safari, use a setInterval() to see if the document has loaded
if (/WebKit/i.test(navigator.userAgent)) {
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(_timer);
init();
}
},10);
}
// For Internet Explorer (using conditional comments) attach a script
// that is deferred to the end of the load process and then check to see
// if it has loaded
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init();
}
};
/*@end @*/
return true;
}
//YUI 2.8
YAHOO.util.Event.onDOMReady( fn , obj , overrideContext )
参数:
fn <function> what to execute when the element is found.
obj <object> an optional object to be passed back as a parameter to fn.
overrideContext <boolean|object>
If set to true, fn will execute in the context of obj, if set to an object it will execute in the context of that object
9.事件处理方法
//自定义函数
/**
* 阻止事件传递
*/
function stopPropagation(eventObject) {
eventObject = eventObject || getEventObject(eventObject);
if(eventObject.stopPropagation) {
eventObject.stopPropagation();
} else {
eventObject.cancelBubble = true;
}
}
window['ADS']['stopPropagation'] = stopPropagation;
/**
* 阻止元素本身的默认事件
*/
function preventDefault(eventObject) {
eventObject = eventObject || getEventObject(eventObject);
if(eventObject.preventDefault) {
eventObject.preventDefault();
} else {
eventObject.returnValue = false;
}
}
/**
* 获得事件对象
*/
function getEventObject(W3CEvent) {
return W3CEvent || window.event;
}
//YUI2.8
YAHOO.util.Event
getEvent
preventDefault
stopPropagation
//前两者之和
stopEvent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment