javascript实用工具方法总结

阅读更多

 

自执行函数(立即执行):

不能直接这样:

function(){
  alert('a');
}()
因为这样会解析出错,需要加上括号:

(function(){
  alert('a');
})()

或者:

(function(){
  alert('a');
}())

 

DOM元素节点:元素节点,属性节点,文本节点

function _nodeFn(domEle){
  if(domEle.nodeType == 1){//元素节点
    alert(domEle.nodeName);//或者tagName
  }else if(domEle.nodeType == 3){//文本节点
    alert(domEle.nodeValue);//文本节点的节点值,即文本内容
  }
}

 

jquery插件的写法:

 

1.对象方法添加:

 

;//写插件的时候,分号是个好的习惯,可以避免其他js没有以分号结束引发的问题

(function($){
  $.fn.extend({
    "color":function(value){//这里面的this表示jquery对象
       return this.css("color",value);//return 是为了仿照jquery的风格,方法返回jquery对象,后面可以链式调用
    }
  });
})(jQuery)

;//我们自己的插件写完之后要加上分号,不给别人造成影响
 
调用方法:
$("_id").color("red");
 

 

 

2.全局方法添加:

 

;//写插件的时候,分号是个好的习惯,可以避免其他js没有以分号结束引发的问题

(function($){
  $.extend({
    "ltrim":function(text){
       return (text || "").replace(/^\s+/g,"");
    }
  });
})(jQuery)

;//我们自己的插件写完之后要加上分号,不给别人造成影响
 

 

调用方法:

 

$.ltrim("   nihao")

 

 

 

浏览器模式(标准模式、怪异模式,主要是针对IE处理)

if(document.compatMode == 'CSS1Compat'){//标准模式
    //document.documentElement 也就是 元素
    alert(document.documentElement.clientWidth);
}else{//怪异模式
   alert(document.body.clientWidth);
}

 

 

将指定的节点滚动到可见的区域:

var ele = document.getElementById('_id');
ele.scrollIntoView();

 

 

 

 

闭包实现累加:

function _increase(){
  var num = 0;
  return function(){
    num++;
    return num;
  }
}
var addFn = _increase();
alert(addFn());
alert(addFn());
alert(addFn());
 

 

 

判断元素class操作:

//判断元素是否含有class属性
function _hasClass(ele,className){
  return !!ele.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}
//元素添加class属性
function _addClass(ele,className){
  if(!_hasClass(ele,className)){
    ele.className += (' '+className);
  }
}
//删除元素指定的class
function deleteClass(ele,className){
  if(_hasClass(ele,className)){
    ele.className = ele.className.replace(new RegExp('(\\s|^)' + className + '(\\s|$)'),' ');
  }
}
例如:
var ele = document.getElementById('_id');
_hasClass(ele,'class1');

 

获取元素相对于文档对象的偏移:

function _getOffset(ele){
  var offset = {
    top:ele.offsetTop,
    left:ele.offsetLeft
  };
  while(ele= ele.offsetParent){
    offset.top += ele.offsetTop;
    offset.left += ele.offsetLeft;
  }
  return offset;
}

 

 

 

 

获取pageX,pageY:

function _pagePosition(e) {
    e = e || window.event;

    var pageX = e.pageX;
    var pageY = e.pageY;
    if (pageX === undefined) {
        pageX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        pageY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
return {'pageX':pageX,'pageY':pageY};
};

 

获取offSetX,offSetY:

function _offSet(e) {
    e = e || window.event;

    var target = e.target || e.srcElement,
        style = target.currentStyle || window.getComputedStyle(target, null),
        borderLeftWidth = parseInt(style['borderLeftWidth'], 10),
        borderTopWidth = parseInt(style['borderTopWidth'], 10),
        rect = target.getBoundingClientRect(),
        offsetX = e.clientX - borderLeftWidth - rect.left,
        offsetY = e.clientY - borderTopWidth - rect.top;

    return {'offsetX':offsetX ,'offsetY':offsetY};
};

 

 

 

元素始终在屏幕居中(jquery):

function _center(ele){
  _this = $(ele);
  _this .css('position','absolute');
  _this .css('top',($(window).height()-_this .height())/2+$(window).scrollTop()+'px');
  _this .css('left',($(window).width()-_this .width())/2+$(window).scrollLeft()+'px');
}

例如:
_center(document.getElementById('_id'));

 

 

 

改变 iframe 背景:

操作页面中的iframe:普通js方式:

 










 

jquery方式:

 

HTML 代码:


jQuery 代码 contents():
$("iframe").contents().find("body").append("I'm in an iframe!");
 

 

 

 

 

 

kindeditor.js 源码:(做学习用)

 

记录:如果想要在编辑器中图片上面禁用右键功能,可以修改源码,加上下面的注释中的内容即可:

 

function _bindContextmenuEvent() {
	var self = this, doc = self.edit.doc;
	K(doc).contextmenu(function(e) {
		/** 在图片上面禁用右键功能  开始*/
		var _ele = e.srcElement || e.target;
		if(_ele.tagName == 'IMG'){
			if (e.preventDefault) {
				e.preventDefault();
			}
			return false;
		}
		/** 在图片上面禁用右键功能  结束*/
		if (self.menu) {
			self.hideMenu();
		}

 

判断是否是IE:

_ua = navigator.userAgent.toLowerCase();
_IE = _ua.indexOf('msie') > -1 && _ua.indexOf('opera') == -1,

 

 

获取浏览器的大小:

function _getScreen(){
    var s = {};
    if(window.innerWidth){
         s.width = window.innerWidth;
         s.height = window.innerHeight;
    }else {//IE
         s.width = document.documentElement.clientWidth;
         s.height = document.documentElement.clientHeight;
    } 
    return s;
}
alert(_getScreen().width+'  ,  '+_getScreen().height)

 

提示框tip div:

function _makeTip(_id){
			$("#"+_id+"").hover(function(e){
				 e = e||window.event;
				 var div = "
"+this.title+"
"; $("body").append(div); $("#_tip_div_id").css({ border:'1px solid black', position:'absolute', left:e.clientX+10+"px", top:e.clientY+10+"px" }); this.mytitle=this.title; this.title=''; },function(e){ e = e||window.event; this.title=this.mytitle; this.mytitle=''; $("#_tip_div_id").remove(); }).mousemove(function(e){ e = e||window.event; $("#_tip_div_id").css({ left:e.clientX+10+"px", top:e.clientY+10+"px" }); }); } 例如html: This is my HTML page.
This is my HTML page. js: $(function(){ _makeTip("_link"); });

 

 

 

元素可拖拽:

 

function _getScreen(){
    var s = {};
    if(window.innerWidth){
         s.width = window.innerWidth;
         s.height = window.innerHeight;
    }else {//IE
         s.width = document.documentElement.clientWidth;
         s.height = document.documentElement.clientHeight;
    } 
    return s;
}
function _dragable(ele){
  ele.onmousedown=function(e){
    e = e || window.event;
    //首先阻止事件传播导致浏览器的默认行为
    if(e.preventDefault){//非IE
       e.preventDefault();
   }else{//IE
       e.returnValue = false;
   }
   var _this = ele;
   var old_mouse_x = e.clientX;//鼠标最初的X坐标
   var old_mouse_y = e.clientY;//鼠标最初的Y坐标
   var old_ele_x = _this.offsetLeft;//元素最初的X坐标
   var old_ele_y = _this.offsetTop;//元素最初的Y坐标
   if(_this.setCapture){
       _this.setCapture();
   }
   
   document.onmousemove=function(e){
         e = e || window.event;
         var new_mouse_x = e.clientX;//鼠标当前X坐标
         var new_mouse_y = e.clientY;//鼠标当前Y坐标
         var new_ele_x = (old_ele_x + new_mouse_x - old_mouse_x);//元素当前X坐标
         var new_ele_y = (old_ele_y + new_mouse_y - old_mouse_y);//元素当前Y坐标
         if(new_ele_x < 0){new_ele_x  = 0;}
         if(new_ele_y < 0){new_ele_y  = 0;}
         if(new_ele_x > (_getScreen().width-_this.offsetWidth)){new_ele_x  = (_getScreen()-_this.offsetWidth);}
         if(new_ele_y > (_getScreen().height-_this.offsetHeight)){new_ele_y  = (_getScreen().height-_this.offsetHeight);}

         _this.style.left = new_ele_x+'px';
         _this.style.top = new_ele_y+'px';

   }

document.onmouseup=function(e){
   e = e || window.event;
   this.onmousemove = null;
   this.onmouseup = null;
   if(_this.releaseCapture){
      _this.releaseCapture();
   }
}

}

}


例如:html:
这是一个可拖拽的div
js: window.onload=function(){ _dragable(document.getElementById("_drag")); }

 

 

 

 

判断是否是数组 、函数:

 

 

function _isArray(val) {
	if (!val) {
		return false;
	}
	return Object.prototype.toString.call(val) === '[object Array]';
}
function _isFunction(val) {
	if (!val) {
		return false;
	}
	return Object.prototype.toString.call(val) === '[object Function]';
}
 

 设置元素透明度:

 

IE:
filter:alpha(Opacity=40)

非IE:
opacity:0.4
 

 

 

 

遍历方法:

 

function _each(obj, fn) {
	if (_isArray(obj)) {
		for (var i = 0, len = obj.length; i < len; i++) {
			if (fn.call(obj[i], i, obj[i]) === false) {
				break;
			}
		}
	} else {
		for (var key in obj) {
			if (obj.hasOwnProperty(key)) {
				if (fn.call(obj[key], key, obj[key]) === false) {
					break;
				}
			}
		}
	}
}

 

 trim 方法:

 

function _trim(str) {
	return str.replace(/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '');
}
 

 

转为16进制(toHex)方法:

 

function _toHex(val) {
	function hex(d) {
		var s = parseInt(d, 10).toString(16).toUpperCase();
		return s.length > 1 ? s : '0' + s;
	}
	return val.replace(/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/ig,
		function($0, $1, $2, $3) {
			return '#' + hex($1) + hex($2) + hex($3);
		}
	);
}
 
获取css样式:
function _css(ele,attr){
     if(typeof window.getComputedStyle != 'undefined'){//W3C
          return window.getComputedStyle(ele,null)[attr];
    }else if(typeof ele.currentStyle != 'undefined'){//IE
          return ele.currentStyle[attr];
    }
}
var ele = document.getElementById('_id');
_css(ele,'width')
 
往link文件中添加CSS样式:
function addRule(num,selectText,cssText,position){
   var sheet = document.styleSheets[num];//获取第num个link文件
   if(typeof sheet.insertRule != 'undefined'){//W3C
        sheet.insertRule(selectText+'{'+cssText+'}',position);
   }else if(typeof sheet.addRule != 'undefined'){//IE
         sheet.addRule(selectText,cssText,position);
   }

}

var ele = document.getElementById('_id');
addRule(0,'body','background:red',0);//在第一个link文件中的第一个位置添加如下的css:    body{background:red}
 

 

绑定/解绑 事件:

 

function _bindEvent(el, type, fn) {
	if (el.addEventListener){
		el.addEventListener(type, fn, false);
	} else if (el.attachEvent){
		el.attachEvent('on' + type, fn);
	}
}
function _unbindEvent(el, type, fn) {
	if (el.removeEventListener){
		el.removeEventListener(type, fn, false);
	} else if (el.detachEvent){
		el.detachEvent('on' + type, fn);
	}
}
 

 

阻止事件传播:

function preventDefault () {
		var ev = this.event;
		if (ev.preventDefault) {
			ev.preventDefault();
		}
		ev.returnValue = false;
	}
function stopPropagation() {
		var ev = this.event;
		if (ev.stopPropagation) {
			ev.stopPropagation();
		}
		ev.cancelBubble = true;
	}
function stop () {
		this.preventDefault();
		this.stopPropagation();
	}

 

设置透明度:

function _opacity (val) {
		this.each(function() {
			if (this.style.opacity === undefined) {
				this.style.filter = val == 1 ? '' : 'alpha(opacity=' + (val * 100) + ')';
			} else {
				this.style.opacity = val == 1 ? '' : val;
			}
		});
		return this;
	}

 

 

固定div在浏览器的位置(用jquery):

 





pic

 

 

 

 

 

删除对象属性:

function _removeId(el) {
	try {
		delete el[_eventExpendo];
	} catch(e) {
		if (el.removeAttribute) {
			el.removeAttribute(_eventExpendo);
		}
	}
}

 

 原型实现继承:

 

构造器(constructor)

    1、constructor始终指向创建当前对象的构造(初始化)函数。
    2、每个函数都有一个默认的属性prototype,而这个prototype的constructor默认指向这个函数

 

所以我们可以通过函数的prototype的constructor属性来查看其构造方法是否正确。

 

 

//通过方法里面的两个alert的内容,可以看出继承之后的构造器仍指向 KWidget ,如果把
//parent.constructor = child;这句话去掉的话,就可以看到继承之后的构造器不再指向 KWidget 
//所以 parent.constructor = child; 这句话是很重要的function _extend(child, parent) {
    parent.constructor = child;//保证继承之后的对象的构造方法的正确性
    alert(KWidget.prototype.constructor)
    child.prototype = parent;//通过prototype实现继承
    alert(KWidget.prototype.constructor)
}
//下面举例看下使用方法
function KWidget() {
	this._name='KWidget  name';
}
_extend(KWidget, {
	init : function() {
	   alert('init');
	}
})
alert(KWidget.prototype.constructor)
 

 

 jquery.cookie实现保存用户名密码(需要将页面放在服务器上访问):

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
    
    My JSP 'index.jsp' starting page
	
	
	    
	
	
	
	
	
  
  
  
    jquery.cookie实现保存用户名密码:
用户名:
密 码:

 

 

 判断键盘回车事件(enter)、使用原生DOM方式获取cookie、设置cookie

 

    function isEnter(ev) {
        ev = ev || window.event;
        var code = (ev.keyCode || ev.which);
        return (code == 10 || code == 13);
    };
    function getCookie(name) {
        var ck = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
        if (ck) return ck[2];
        else return null;
    };
    function setCookie (name, value, expires) {
        if (expires) expires = '; expires=' + new Date(expires).toUTCString();
        else expires = '';
        var path = '; path=/';
        var domain = '; domain=' + document.domain.replace('www.', '');

        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain].join('');
    }

 

 

 jquery unbind hover 解绑 hover事件处理:

 

//这种方式是错误的
$("#hover_div").unbind("hover");

//这种方式也是错误的
$("#hover_div").unbind("mouseover").unbind("mouseout");

//这种方式是新增的,在老的版本里是无法使用的
$("#hover_div").unbind("mouseenter mouseleave");

//正确的,新老版本都可用
$("#hover_div").unbind("mouseenter").unbind("mouseleave");

 

 

jquery中 bind、live、delegate 的区别 (参考 : jQuery三种事件绑定方式.bind(),.live(),.delegate()):
bind是将事件直接绑定到目标元素上面;
live是绑定到document上面,当时间冒泡到document的时候,通过判断事件的类型和来源是否符合条件作出处理

delegate 可以用来替换live ; 例如:$('a').live('click', function() { blah() }); 可以使用 $(document).delegate('a', 'click', function() { blah() }); 来替换。

但是deletegate要比live效率高点,因为 $('a') .live.... 会先遍历整个文档查找符合条件的a 元素,然后保存起来,而delegate 只需要找到 document 就可以了。。。

这个缺陷可以通过  在 $(document).ready()之前调用live方法,这样就会立即执行。这时候DOM还没有填充,也就不会查找元素或创建jQuery对象

 

格式化数字,变为没三位数字中间隔一个逗号:

 

/**
 * 数字显示格式(每三位中间用逗号隔开),方法功能有限,对于超大的数字不能正确处理
 */
function formatNumber(num) {
	//数字变为字符串
	num = (num + '');
	//数组长度
	var length = num.length;
	//计算出循环的次数
	var n = length%3 == 0 ? length/3 : (length/3+1);
	//将循环次数变为整数
	n = parseInt(n+'');
	var arr = [];
	var startIndex;
	var endIndex;
	var subStr = '';
	for(var i=0;i= 0 ? (endIndex-3) : 0;
		subStr = num.substring(startIndex,endIndex);
		arr.push(subStr);
	}
	//由于字符串是倒叙截取的,最后需要翻转一下,让数字的顺序是从大到小的
	arr = arr.reverse();
	return arr.join(',');
}

 

 

 CSS设置浮动float的时候,IE浏览器兼容模式出现换行的解决方法:(总结下来就是讲浮动元素放在非浮动元素前面)

 

例如,我们使用下面方式浮动的时候在IE兼容模式会出现换行:

内容a 浮动内容

 此时,内容a和浮动内容不在一行

 

这是因为如果浮动内容浮动的时候,如果非float元素在前的话,float元素会被排斥

 

要解决这个问题,只需要将float的元素放在非float元素的前面就好了:

浮动内容内容a

 

 

上面是以右浮动为例,左浮动也是一样的:

例如:

其他内容xxx左边浮动内容

 这样会出现换行现象(IE)

 

只需要换下位置就好了,将float元素放在前面:

左边浮动内容其他内容xxx

 

 

jQuery触发超链接click事件:

 

html代码:

百度一下

 

 

直接通过这种方式是不行的:

 

$("a").click();

 

要通过下面两种方式都行:

 

方法1.通过获取第一个元素来触发(DOM):

 

$("a").get(0).click();

 

 

方法2.在超链接中加入标签:

 

百度一下

 

然后通过下面方式触发:

 

$("a span").click();

 

 

 jquery get(n)  eq(n) 区别:

 

$(this).get(0)与$(this)[0]相同;get返回的结果是dom对象,eq返回的结果是jquery对象

 

 

js String replace 替换字符串的时候,如果有反斜杠的时候出现的问题:(下面把src的值替换为*号):下面是不行的

 

var str="";
var oldStr = "myFolder\\myFile.txt";
var newStr = "******";
alert(str.replace(new RegExp(oldStr,'g'),newStr));

 

需要做一些修改:

 

var str="";
var oldStr = "myFolder\\myFile.txt";
//和java一样,正则里面的反斜杠要用转义字符处理
oldStr = oldStr.replace(/\\/g,'\\\\');
var newStr = "******";
alert(str.replace(new RegExp(oldStr,'g'),newStr));

 

ExtJs extend:

function Parent(){

};

function Child(){

};

function my_extend(parent, child){
	function Temp(){
	
	}
	// share parent's prototype with Temp
	Temp.prototype = parent.prototype;
	// change child's prototype
	child.prototype = new Temp();
	// change child's prototype's constructor
	child.prototype.constructor = child;
	// save parent's prototype on child
	child.super_prototype = parent.prototype;
	
	// ensure parent's prototype's constructor is not Object
	if(parent.prototype.constructor === Object.prototype.constructor){
		parent.prototype.constructor = parent;
	}
};

// invoke
my_extend(Parent, Child);

 

 

  • kindeditor.rar (35.9 KB)
  • 下载次数: 4

你可能感兴趣的:(javascript,kindeditor,工具,方法)