總結-前端開發常用簡單的js方法
在開發過程中進場用到總結出來的一些方法,手機整理,希望能給大家帶來幫助,如有錯誤,歡迎指正。
/*驗證手機號碼*/
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;
}
}
//匹配身份證(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 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);
}
/*獲取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;
}
// 獲取當前日期加時間(如:2017-12-12 12.00)
function CurentTime()
{
var now = new Date();
var year = now.getFullYear(); //年
var month = now.getMonth() + 1; //月
var day = now.getDate(); //日
var hh = now.getHours(); //時
var mm = now.getMinutes(); //分
var clock = year + "-";
if(month < 10)
clock += "0";
clock += month + "-";
if(day < 10)
clock += "0";
clock += day + " ";
if(hh < 10)
clock += "0";
clock += hh + ":";
if (mm < 10) clock += '0';
clock += mm;
alert(clock);
}