都是一些在自己的开发过程中经常用到总结出来的一些方法,也有部分收集整理,希望能给大家带来帮助,如有错误,欢迎指正。
部分方法依赖于Jq,请自行引入
//tab切换
/*
* 参数tablist为触发事件id
* 参数tabmain为执行切换id
* 参数ev为触发事件的动作
*/
function tab(tablist,tabmain,ev){
$(tablist).bind(ev,function(){
var mythis= this;
var n= $(this).index();
$($(this).siblings()).removeClass("active");
$(this).addClass("active");
$(tabmain).removeClass("active");
$($(tabmain)[n]).addClass("active");
});
}
//重写移动端触屏点击(无延迟)
$.fn.ontouch = function(callback,bool){
var _x,_y,_s,
_t = {
s : function(event){
var t = getTouch(event);
_x = t.clientX;
_y = t.clientY;
_s = true;
},
m : function(event){
if(_s){
var t = getTouch(event);
if(_x != t.clientX || _y != t.clientY){
_s = false;
}
}
},
e : function(event){
if(_s){
callback.call(this);
if(bool){
event.preventDefault();
return false;
}
}
}
};
function getTouch(event){
return event.originalEvent.touches[0] ? event.originalEvent.touches[0] : event;
};
this.bind({
"touchstart" : _t.s,
"touchmove" : _t.m,
"touchend" : _t.e
});
return this;
};
/*验证手机号码*/
function isTelNum(str){
var _tel = $.trim(str),
_reg = /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
return _reg.test(_tel);
};
/*验证邮件地址*/
function isEmail (value, target) {
value = value.trim();
if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(value)) {
target.val("");
return true;
}
}
//匹配国内电话号码(0511-4405222 或 021-87888822)
function istell(str) {
var result = str.match(/\d{3}-\d{8}|\d{4}-\d{7}/);
if (result == null) return false;
return true;
}
//匹配身份证(15位或18位)
function isidcard(str) {
var result = str.match(/\d{15}|\d{18}/);
if (result == null) return false;
return true;
}
//判断是否移动设备访问
function isMobileUserAgent() {
return (/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(window.navigator.userAgent.toLowerCase()));
}
//完美判断是否为网址
function IsURL(strUrl) {
var regular = /^\b(((https?|ftp):\/\/)?[-a-z0-9]+(\.[-a-z0-9]+)*\.(?:com|edu|gov|int|mil|net|org|biz|info|name|museum|asia|coop|aero|[a-z][a-z]|((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d))\b(\/[-a-z0-9_:\@&?=+,.!\/~%\$]*)?)$/i
if (regular.test(strUrl)) {
return true;
} else {
return false;
}
}
/*
*移动端简单监听滑动方向方法
*/
// 返回角度
function GetSlideAngle(dx, dy) {
return Math.atan2(dy, dx) * 180 / Math.PI;
}
//根据起点和终点返回方向 1:向上,2:向下,3:向左,4:向右,0:未滑动
function GetSlideDirection(startX, startY, endX, endY) {
var dy = startY - endY;
var dx = endX - startX;
var result = 0;
//如果滑动距离太短
if(Math.abs(dx) < 50 && Math.abs(dy) <50) {
return result;
}
var angle = GetSlideAngle(dx, dy);
if(angle >= -45 && angle < 45) {
result = 4;
}else if (angle >= 45 && angle < 135) {
result = 1;
}else if (angle >= -135 && angle < -45) {
result = 2;
}
else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) {
result = 3;
}
return result;
}
function touchMove() {
//滑动处理
var startX, startY;
var a = document.getElementById("room_img")? document.getElementById("room_img"):document;
a.addEventListener('touchstart',function (ev) {
startX = ev.touches[0].pageX;
startY = ev.touches[0].pageY;
}, false);
a.addEventListener('touchend',function (ev) {
var endX, endY;
endX = ev.changedTouches[0].pageX;
endY = ev.changedTouches[0].pageY;
var direction = GetSlideDirection(startX, startY, endX, endY);
switch(direction) {
case 0:
// alert("没滑动");
break;
case 1:
console.log("向上");
break;
case 2:
console.log("向下");
break;
case 3:
console.log("向左");
break;
case 4:
console.log("向右");
break;
default:
}
}, false);
}
/*正则替换text/plain*/
$.replace = function(temp, data, regexp){
if(!(Object.prototype.toString.call(data) === "[object Array]")) data = [data];
var ret = [];
for(var i=0,j=data.length;i<j;i++){
ret.push(replaceAction(data[i]));
}
return ret.join("");
function replaceAction(object){
return temp.replace(regexp || (/\\?\{([^}]+)\}/g), function(match, name){
if (match.charAt(0) == '\\') return match.slice(1);
return (object[name] != undefined) ? object[name] : '';
});
}
};
/*简单使用案例
<html>
<script type="text/plain" id="testDemo">
<div>{a}</div>
<span>{b}<span>
</script>
<script type="text/javascript">
var data = {"a":"a","b":"b"};
var html = replace("testDemo",data);
$("html").append(html);
</script>
</html>
*/
/*获取url参数*/
function GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)return unescape(r[2]); return null;
}
/*输入框焦点获取和失去时显示默认文字*/
function input_focus (inputId) {
$(inputId).bind({
focus:function(){
if (this.value == this.defaultValue){
this.value="";
}
},
blur:function(){
if (this.value == ""){
this.value = this.defaultValue;
}
}
});
}
/*阻止事件冒泡*/
function stopEvent(event){
//取消事件冒泡
var e=arguments.callee.caller.arguments[0]||event; //若省略此句,下面的e改为event,IE运行可以,但是其他浏览器就不兼容
if (e && e.stopPropagation) {
// this code is for Mozilla and Opera
e.stopPropagation();
} else if (window.event) {
// this code is for IE
window.event.cancelBubble = true;
}
}
//写cookies
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
//读cookie
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}
/*仿原生app滑动切换*/
//html结构
// <div class="focus_map" id="tabs">
// <div class="border">
// <ul class="atlas">
// </ul>
// </div>
// </div>
//css样式
// .focus_map { height: 3.2rem; position: relative; overflow: hidden; }
// .focus_map .border { height: 100%; width: 100%; overflow: hidden; }
// .focus_map ul { width: 200rem; height: 100%; }
// .focus_map li { width: 7.5rem; height: 100%; overflow: hidden; -webkit-overflow-scrolling: touch; }
// .focus_map img { width: 100%; vertical-align: middle; }
// .focus_map nav { position: absolute; left: 0; bottom: .15rem; width: 100%; text-align: center; }
// .focus_map nav i { display: inline-block; margin: 0 .1rem; border-radius: 50%; width: .16rem; height: .16rem; border-radius: .25rem; background: #bbbbbb; }
// .focus_map nav i.cur { background: #1f80b8; }
function focusbind(){
//对象&变量 缓存
var $tab = $("#tabs"),
$ul = $tab.find("ul"),
$li = $ul.children(),
$nav = $("<nav>"),
li_len = $li.length,
li_w = $li.eq(0).width();
//容器 初始化
$li.css({
"float" : "left",
"width" : li_w
})
.each(function(i){
var str = i == 0 ? "<i class=\"cur\">" : "<i>";
$nav.append(str);
});
$nav.appendTo($tab);
$li.eq(0).clone().appendTo($ul);
$li.eq(-1).clone().css("marginLeft",-li_w).prependTo($ul);
$ul.css("float","left").width(li_w * $ul.children().length);
//切换 方法
var eventOff,startX,clientX,
index = 0,
eventMaxWidth = li_w,
objStatus = {},
eventTo,
time=5000,
tab = {
//开始
start : function (event){
//重置水平位置
clientX = 0;
//滑动激活
eventOff = true;
//获取鼠标||触点水平坐标
var touch = event.touches && event.touches[0] || event;
//记录初始坐标
startX = touch.clientX;
//记录切换前对象状态
objStatus.left = $ul.get(0).style.marginLeft;
//阻止对象默认行为
// event.preventDefault();
console.log("准备切换");
clearInterval(eventTo);
},
//移动
move : function (event){
var touch = event.touches && event.touches[0] || event,
_x = touch.clientX - startX;
if(eventOff){
clientX = parseInt(_x/eventMaxWidth * 100);
$ul.get(0).style.marginLeft = (li_w * clientX / 100) - li_w * index + "px";
//console.log("滑动进度:" + clientX + "%");
}
event.preventDefault();
},
//结束
end : function (event){
var _clientX = clientX > 0 ? clientX : -(clientX);
//滑动激活,且滑动百分比超过50
if(eventOff){
if(_clientX >= 30){
index = clientX > 0 ? index - 1 : index + 1;
tab.to();
console.log("切换完成");
}
else{
console.log("放弃切换");
$ul.animate({
"marginLeft" : objStatus.left
});
}
eventOff = false;
}
eventTo = setInterval(function(){
index++;
tab.to();
},time);
// event.preventDefault();
},
to:function(){
var moveCallback;
objStatus.left = -(li_w * index) + "px";
//复位
if(index >= li_len){
index = 0;
moveCallback = function(){
$ul.get(0).style.marginLeft = -(li_w * index) + "px";
};
}
else if(index < 0){
index = li_len - 1;
moveCallback = function(){
$ul.get(0).style.marginLeft = -(li_w * index) + "px";
};
}
$nav.children().eq(index).addClass("cur").siblings().removeClass("cur");
$ul.animate({
"marginLeft" : objStatus.left
},moveCallback);
}
};
eventTo = setInterval(function(){
index++;
tab.to();
},time);
//触摸事件 注册
$tab.get(0).addEventListener("touchstart",tab.start,false);
$tab.get(0).addEventListener("touchmove",tab.move,false);
$tab.get(0).addEventListener("touchend",tab.end,false);
}
/*原生js获取class*/
function getElementByClassName(classnames){
var objArray= new Array();//定义返回对象数组
var tags=document.getElementsByTagName("*");//获取页面所有元素
var index = 0;
for(var i in tags){
if(tags[i].nodeType==1){
if(tags[i].getAttribute("class") == classnames){ //如果某元素的class值为所需要
objArray[index]=tags[i];
index++;
}
}
}
return objArray;
}
//获取鼠标的位置。兼容ie678
function getXY(e){
var ev = e || window.event;
var x=0,y=0;
if(ev.pageX){
x = ev.pageX;
y = ev.pageY;
}else{
//拿到scrollTop 和scrollLeft
var sleft = 0,stop = 0;
//ie678---
if(document.documentElement){
stop =document.documentElement.scrollTop;
sleft = document.documentElement.scrollLeft;
}else{
//ie9+ 谷歌
stop = document.body.scrollTop;
sleft = document.body.scrollLeft;
}
x = ev.clientX + sleft;
y = ev.clientY + stop;
}
return {x:x,y:y};
};
//范围随机数
function randomRange(start,end){
return Math.floor(Math.random()*(end-start+1))+start;
};
//随机颜色
function randomColor(){
var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
return "rgb("+r+","+g+","+b+")";//IE7不支出rgb
};
/*是否为微信浏览器*/
function isWeiXin(){
var ua = window.navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i) == 'micromessenger'){
return true;
}else{
return false;
}
}
/*Jq获取屏幕各种高度*/
$(document).ready(function(){
alert($(window).height()); //浏览器当前窗口可视区域高度
alert($(document).height()); //浏览器当前窗口文档的高度
alert($(document.body).height());//浏览器当前窗口文档body的高度
alert($(document.body).outerHeight(true));//浏览器当前窗口文档body的总高度 包括border padding margin
alert($(window).width()); //浏览器当前窗口可视区域宽度
alert($(document).width());//浏览器当前窗口文档对象宽度
alert($(document.body).width());//浏览器当前窗口文档body的宽度
alert($(document.body).outerWidth(true));//浏览器当前窗口文档body的总宽度 包括border padding margin
})
/*固定时间的倒计时*/
function countdown(){
var endtime = newDate("Jan 18, 2015 23:50:00");
var nowtime = newDate();
if (nowtime >= endtime) {
document.getElementById("_lefttime").innerHTML = "倒计时间结束";
return;
}
var leftsecond = parseInt((endtime.getTime() - nowtime.getTime()) / 1000);
if (leftsecond < 0) {
leftsecond = 0;
}
__d = parseInt(leftsecond / 3600 / 24);
__h = parseInt((leftsecond / 3600) % 24);
__m = parseInt((leftsecond / 60) % 60);
__s = parseInt(leftsecond % 60);
document.getElementById("_lefttime").innerHTML = __d + "天" + __h + "小时" + __m + "分" + __s + "秒";
}
countdown();
setInterval(countdown, 1000);
/*控制浏览器进入全屏模式*/
function fullScreen() {
var el = document.documentElement,
rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen,
wscript;
if(typeof rfs != "undefined" && rfs) {
rfs.call(el);
return;
}
if(typeof window.ActiveXObject != "undefined") {
wscript = new ActiveXObject("WScript.Shell");
if(wscript) {
wscript.SendKeys("{F11}");
}
}
}
/*退出全屏模式*/
function exitFullScreen() {
var el = document,
cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen,
wscript;
if (typeof cfs != "undefined" && cfs) {
cfs.call(el);
return;
}
if (typeof window.ActiveXObject != "undefined") {
wscript = new ActiveXObject("WScript.Shell");
if (wscript != null) {
wscript.SendKeys("{F11}");
}
}
}
/*字符串超出省略 */
String.prototype.cutstr = function (len) {
var restr = this;
var wlength = this.replace(/[^\x00-\xff]/g, "**").length;
if (wlength > len) {
for (var k = len / 2; k < this.length; k++) {
if (this.substr(0, k).replace(/[^\x00-\xff]/g, "**").length >= len) {
restr = this.substr(0, k) + "...";
break;
}
}
}
return restr;
}
// 返回字符串的实际长度, 一个汉字算2个长度
String.prototype.strlen = function () {
return this.replace(/[^\x00-\xff]/g, "**").length;
}
//转义html标签
function HtmlEncode(text) {
return text.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>')
}