言
本人去年寫了一個PHP偽原創的工具,但是有時候還需要查看一下偽原創后的文章原創度,換句話說在搜索引擎上是否有類似的文章。
本次原創度檢測源代使用百度搜索為準。
首先拼湊百度搜索的url,并且百度限制了搜索詞在38個漢字以內,其他的會被丟棄。
https://www.baidu.com/s?ie=utf8&wd=關鍵詞
好了,現在百度搜索的url也有了,那怎么檢查一篇文章的原創度了?
PHPcurl訪問函數源代碼
function curl($url){
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$httpheader[]="Accept:*/*";
$httpheader[]="Accept-Encoding:gzip,deflate,sdch";
$httpheader[]="Accept-Language:zh-CN,zh;q=0.8";
$httpheader[]="Connection:close";
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3314.0 Safari/537.36 SE 2.X MetaSr 1.0');
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$ret=curl_exec($ch);
curl_close($ch);
return $ret;
}
首先要把一篇文章的所有html標簽去掉,那就需要使用以下代碼,去除無用的html和字符了。
function ClearHtml($str){
$str=trim($str);
$str=strip_tags($str,"");
$str=preg_replace("/\t/","",$str);
$str=preg_replace("/\r\n/","",$str);
$str=preg_replace("/\r/","",$str);
$str=preg_replace("/\n/","",$str);
$str=preg_replace("/ /","",$str);
$str=preg_replace("/ /","",$str);
return trim($str);
}
然后就要把重新整理好的文章分隔成為每38個漢字為一組的數組,所使用的代碼為
function mbStrSplit ($string, $len=38) {
$start=0;
$strlen=mb_strlen($string);
while ($strlen) {
$array[]=mb_substr($string,$start,$len,"utf8");
$string=mb_substr($string, $len, $strlen,"utf8");
$strlen=mb_strlen($string);
}
return $array;
}
如果你的PHP環境為PHP7.4可直接使用以下內置函數把文章分割為38個漢字為一組,不過我這里是使用的上面的,暫時沒有搭建最新的PHP環境。
mb_str_split ( string $string [, int $split_length=1 [, string $encoding=mb_internal_encoding() ]] ) : array
注:https://www.php.net/manual/zh/function.mb-str-split.php
以下為文章中其中一個38個漢字的原創度獲取源代碼,我就不一一解釋了,我感覺我這里代碼寫的不太好,如果您有優化好的,請回復,謝謝。
function bdycl($content){
$info=curl('https://www.baidu.com/s?ie=utf8&wd='.urlencode($content));
preg_match_all("/<div class=\"c-abstract\">(.*?)<\/div>(.*?)href=\"(.*?)\"/is", $info,$baidu);
$count1=count($baidu['1']);
for($i=0;$i<$count1;$i++){
preg_match_all("/<em>(.*?)<\/em>/is", $baidu['1'][$i],$baidu_em);
$count=count($baidu_em[1]);
if($count>1){
$baiduem='';
foreach($baidu_em[1] as $value){
$baiduem.=$value;
}
$bdem[]=[
'content'=>$baiduem,
'url'=>$baidu['3'][$i]
];
}else{
$bdem[]=[
'content'=>@$baidu_em[1][0],
'url'=>$baidu['3'][$i]
];
}
}
if(is_array($bdem)){
$count=count($bdem);
$in=[];
for($i=0;$i<$count;$i++){
similar_text($content,$bdem[$i]['content'],$per);
$ii=ceil($per);
$similar[]=$ii;
if($ii>90){
$in[]=[
'similar'=>$ii,
"content"=>$bdem[$i]['content'],
'url'=>$bdem[$i]['url']
];
}
}
array_multisort(array_column($in,'similar'),SORT_DESC,$in);
if(isset($in['0'])){
$in=$in['0'];
}
return ['similar'=>(100-array_sum($similar)/count($bdem)),'content'=>$in];
}
}
單獨一個原創度檢測
單獨一組38個漢字咱們已經寫完了,現在需要來一個查詢多組的。以下為源代碼
function ycl($content){
$info=mbStrSplit($content);
$count=count($info)-1;
if($count<11){
$rand=$count+1;
}else{
$rand='10';
}
$tmp=range(0,$count);
$array_rand=array_rand($tmp,$rand);
foreach($array_rand as $v){
$ycl[]=bdycl($info[$v]);
}
$count=count($ycl);
for($i=0;$i<$count;$i++){
$similar[$i]=$ycl[$i]['similar'];
}
$ycd=ceil(((array_sum($similar)/count($ycl))));
if($ycd <=30){
$str="原創度非常低,不建議發布。";
}else if($ycd <=60 && $ycd > 30){
$str="原創度比較低,建議修改后再發布。";
}else if($ycd <=75 && $ycd > 60){
$str="原創度還可以,建議修改后再發布。";
}else if($ycd <=85 && $ycd > 75){
$str="原創度較好,屬于原創文章,可以發布。";
}else if($ycd > 85){
$str="原創度非常棒,屬于原創文章,可以發布。";
}
return ['ycl'=>$ycd,'info'=>$str];
}
然后隨便從網上找一篇文章,進行檢測的結果為:
TML
語法
- 用兩個空格來代替制表符(tab) -- 這是唯一能保證在所有環境下獲得一致展現的方法。
- 嵌套元素應當縮進一次(即兩個空格)。
- 對于屬性的定義,確保全部使用雙引號,絕不要使用單引號。
- 不要在自閉合(self-closing)元素的尾部添加斜線 -- HTML5 規范中明確說明這是可選的。
- 不要省略可選的結束標簽(closing tag)(例如,</li>或 </body>)。
<!DOCTYPE html> <html> <head> <title>Page title</title> </head> <body> <img src="images/company-logo.png" alt="Company"> <h1 class="hello-world">Hello, world!</h1> </body> </html>
HTML5 doctype
為每個 HTML 頁面的第一行添加標準模式(standard mode)的聲明,這樣能夠確保在每個瀏覽器中擁有一致的展現。
<!DOCTYPE html> <html> <head> </head> </html>
語言屬性
根據 HTML5 規范:
強烈建議為 html 根元素指定 lang 屬性,從而為文檔設置正確的語言。這將有助于語音合成工具確定其所應該采用的發音,有助于翻譯工具確定其翻譯時所應遵守的規則等等。
<html lang="en-us"> <!-- ... --> </html>
IE 兼容模式
IE 支持通過特定的 <meta> 標簽來確定繪制當前頁面所應該采用的 IE 版本。除非有強烈的特殊需求,否則最好是設置為 edge mode,從而通知 IE 采用其所支持的最新的模式。
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
字符編碼
通過明確聲明字符編碼,能夠確保瀏覽器快速并容易的判斷頁面內容的渲染方式。這樣做的好處是,可以避免在 HTML 中使用字符實體標記(character entity),從而全部與文檔編碼一致(一般采用 UTF-8 編碼)。
<head> <meta charset="UTF-8"> </head>
引入 CSS 和 JavaScript 文件
根據 HTML5 規范,在引入 CSS 和 JavaScript 文件時一般不需要指定 type 屬性,因為 text/css 和 text/javascript分別是它們的默認值。
<!-- External CSS --> <link rel="stylesheet" href="code-guide.css"> <!-- In-document CSS --> <style> /* ... */ </style> <!-- JavaScript --> <script src="code-guide.js"></script>
屬性順序
HTML 屬性應當按照以下給出的順序依次排列,確保代碼的易讀性。
- class
- id, name
- data-*
- src, for, type, href, value
- title, alt
- role, aria-*
class 用于標識高度可復用組件,因此應該排在首位。id 用于標識具體組件,應當謹慎使用(例如,頁面內的書簽),因此排在第二位。
<a class="..." id="..." data-toggle="modal" href="#"> Example link </a> <input class="form-control" type="text"> <img src="..." alt="...">
布爾(boolean)型屬性
布爾型屬性可以在聲明時不賦值。XHTML 規范要求為其賦值,但是 HTML5 規范不需要。
元素的布爾型屬性如果有值,就是 true,如果沒有值,就是 false。
如果一定要為其賦值的話,請參考 WhatWG 規范:
如果屬性存在,其值必須是空字符串或 [...] 屬性的規范名稱,并且不要在首尾添加空白符。
簡單來說,就是不用賦值。
<input type="text" disabled> <input type="checkbox" value="1" checked> <select> <option value="1" selected>1</option> </select>
減少標簽的數量
編寫 HTML 代碼時,盡量避免多余的父元素。很多時候,這需要迭代和重構來實現。請看下面的案例:
<!-- Not so great --> <span class="avatar"> <img src="..."> </span> <!-- Better --> <img class="avatar" src="...">
JavaScript 生成的標簽
通過 JavaScript 生成的標簽讓內容變得不易查找、編輯,并且降低性能。能避免時盡量避免。
CSS
語法
- 用兩個空格來代替制表符(tab) -- 這是唯一能保證在所有環境下獲得一致展現的方法。
- 為選擇器分組時,將單獨的選擇器單獨放在一行。
- 為了代碼的易讀性,在每個聲明塊的左花括號前添加一個空格。
- 聲明塊的右花括號應當單獨成行。
- 每條聲明語句的 : 后應該插入一個空格。
- 為了獲得更準確的錯誤報告,每條聲明都應該獨占一行。
- 所有聲明語句都應當以分號結尾。最后一條聲明語句后面的分號是可選的,但是,如果省略這個分號,你的代碼可能更易出錯。
- 對于以逗號分隔的屬性值,每個逗號后面都應該插入一個空格(例如,box-shadow)。
- 不要在 rgb()、rgba()、hsl()、hsla() 或 rect() 值的內部的逗號后面插入空格。這樣利于從多個屬性值(既加逗號也加空格)中區分多個顏色值(只加逗號,不加空格)。
- 對于屬性值或顏色參數,省略小于 1 的小數前面的 0 (例如,.5 代替 0.5;-.5px 代替 -0.5px)。
- 十六進制值應該全部小寫,例如,#fff。在掃描文檔時,小寫字符易于分辨,因為他們的形式更易于區分。
- 盡量使用簡寫形式的十六進制值,例如,用 #fff 代替 #ffffff。
- 為選擇器中的屬性添加雙引號,例如,input[type="text"]。只有在某些情況下是可選的,但是,為了代碼的一致性,建議都加上雙引號。
- 避免為 0 值指定單位,例如,用 margin: 0; 代替 margin: 0px;。
/* Bad CSS */ .selector, .selector-secondary, .selector[type=text] { padding:15px; margin:0px 0px 15px; background-color:rgba(0, 0, 0, 0.5); box-shadow:0px 1px 2px #CCC,inset 0 1px 0 #FFFFFF } /* Good CSS */ .selector,.selector-secondary,.selector[type="text"] { padding: 15px; margin-bottom: 15px; background-color: rgba(0,0,0,.5); box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff; }
聲明順序
相關的屬性聲明應當歸為一組,并按照下面的順序排列:
- Positioning
- Box model
- Typographic
- Visual
由于定位(positioning)可以從正常的文檔流中移除元素,并且還能覆蓋盒模型(box model)相關的樣式,因此排在首位。盒模型排在第二位,因為它決定了組件的尺寸和位置。
其他屬性只是影響組件的內部(inside)或者是不影響前兩組屬性,因此排在后面。
.declaration-order { /* Positioning */ position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 100; /* Box-model */ display: block; float: right; width: 100px; height: 100px; /* Typography */ font: normal 13px "Helvetica Neue", sans-serif; line-height: 1.5; color: #333; text-align: center; /* Visual */ background-color: #f5f5f5; border: 1px solid #e5e5e5; border-radius: 3px; /* Misc */ opacity: 1; }
不要使用 @import
與 <link> 標簽相比,@import 指令要慢很多,不光增加了額外的請求次數,還會導致不可預料的問題。替代辦法有以下幾種:
- 使用多個 <link> 元素
- 通過 Sass 或 Less 類似的 CSS 預處理器將多個 CSS 文件編譯為一個文件
- 通過 Rails、Jekyll 或其他系統中提供過 CSS 文件合并功能
<!-- Use link elements --> <link rel="stylesheet" href="core.css"> <!-- Avoid @imports --> <style> @import url("more.css"); </style>
媒體查詢(Media query)的位置
將媒體查詢放在盡可能相關規則的附近。不要將他們打包放在一個單一樣式文件中或者放在文檔底部。如果你把他們分開了,將來只會被大家遺忘。下面給出一個典型的實例。
.element { ... } .element-avatar { ... } .element-selected { ... } @media (min-width: 480px) { .element { ...} .element-avatar { ... } .element-selected { ... } }
帶前綴的屬性
當使用特定廠商的帶有前綴的屬性時,通過縮進的方式,讓每個屬性的值在垂直方向對齊,這樣便于多行編輯。
在 Textmate 中,使用 Text → Edit Each Line in Selection(??A)。在 Sublime Text 2 中,使用 Selection → Add Previous Line (??↑) 和 Selection → Add Next Line(??↓)。
/* Prefixed properties */ .selector { -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.15); box-shadow: 0 1px 2px rgba(0,0,0,.15); }
單行規則聲明
對于只包含一條聲明的樣式,為了易讀性和便于快速編輯,建議將語句放在同一行。對于帶有多條聲明的樣式,還是應當將聲明分為多行。
這樣做的關鍵因素是為了錯誤檢測 -- 例如,CSS 校驗器指出在 183 行有語法錯誤。如果是單行單條聲明,你就不會忽略這個錯誤;如果是單行多條聲明的話,你就要仔細分析避免漏掉錯誤了。
/* Single declarations on one line */ .span1 { width: 60px; } .span2 { width: 140px; } .span3 { width: 220px; } /* Multiple declarations, one per line */ .sprite { display: inline-block; width: 16px; height: 15px; background-image: url(../img/sprite.png); } .icon { background-position: 0 0; } .icon-home { background-position: 0 -20px; } .icon-account { background-position: 0 -40px; }
簡寫形式的屬性聲明
在需要顯示地設置所有值的情況下,應當盡量限制使用簡寫形式的屬性聲明。常見的濫用簡寫屬性聲明的情況如下:
- padding
- margin
- font
- background
- border
- border-radius
大部分情況下,我們不需要為簡寫形式的屬性聲明指定所有值。例如,HTML 的 heading 元素只需要設置上、下邊距(margin)的值,因此,在必要的時候,只需覆蓋這兩個值就可以。過度使用簡寫形式的屬性聲明會導致代碼混亂,并且會對屬性值帶來不必要的覆蓋從而引起意外的副作用。
/* Bad example */ .element { margin: 0 0 10px; background: red; background: url("image.jpg"); border-radius: 3px 3px 0 0; } /* Good example */ .element { margin-bottom: 10px; background-color: red; background-image: url("image.jpg"); border-top-left-radius: 3px; border-top-right-radius: 3px; }
Less 和 Sass 中的嵌套
避免不必要的嵌套。這是因為雖然你可以使用嵌套,但是并不意味著應該使用嵌套。只有在必須將樣式限制在父元素內(也就是后代選擇器),并且存在多個需要嵌套的元素時才使用嵌套。
// Without nesting .table > thead > tr > th { … } .table > thead > tr > td { … } // With nesting .table > thead > tr { > th { … } > td { … } }
Less 和 Sass 中的操作符
為了提高可讀性,在圓括號中的數學計算表達式的數值、變量和操作符之間均添加一個空格。
// Bad example .element { margin: 10px 0 @variable*2 10px; } // Good example .element { margin: 10px 0 (@variable * 2) 10px; }
注釋
代碼是由人編寫并維護的。請確保你的代碼能夠自描述、注釋良好并且易于他人理解。好的代碼注釋能夠傳達上下文關系和代碼目的。不要簡單地重申組件或 class 名稱。
對于較長的注釋,務必書寫完整的句子;對于一般性注解,可以書寫簡潔的短語。
/* Bad example */ /* Modal header */ .modal-header { ... } /* Good example */ /* Wrapping element for .modal-title and .modal-close */ .modal-header { ... }
class 命名
- class 名稱中只能出現小寫字符和破折號(dashe)(不是下劃線,也不是駝峰命名法)。破折號應當用于相關 class 的命名(類似于命名空間)(例如,.btn 和 .btn-danger)。
- 避免過度任意的簡寫。.btn 代表 button,但是 .s 不能表達任何意思。
- class 名稱應當盡可能短,并且意義明確。
- 使用有意義的名稱。使用有組織的或目的明確的名稱,不要使用表現形式(presentational)的名稱。
- 基于最近的父 class 或基本(base) class 作為新 class 的前綴。
- 使用 .js-* class 來標識行為(與樣式相對),并且不要將這些 class 包含到 CSS 文件中。
- 在為 Sass 和 Less 變量命名時也可以參考上面列出的各項規范。
/* Bad example */ .t { ... } .red { ... } .header { ... } /* Good example */ .tweet { ... } .important { ... } .tweet-header { ... }
選擇器
- 對于通用元素使用 class ,這樣利于渲染性能的優化。
- 對于經常出現的組件,避免使用屬性選擇器(例如,[class^="..."])。瀏覽器的性能會受到這些因素的影響。
- 選擇器要盡可能短,并且盡量限制組成選擇器的元素個數,建議不要超過 3 。
- 只有在必要的時候才將 class 限制在最近的父元素內(也就是后代選擇器)(例如,不使用帶前綴的 class 時 -- 前綴類似于命名空間)。
/* Bad example */ span { ... } .page-container #stream .stream-item .tweet .tweet-header .username { ... } .avatar { ... } /* Good example */ .avatar { ... } .tweet-header .username { ... } .tweet .avatar { ... }
代碼組織
- 以組件為單位組織代碼段。
- 制定一致的注釋規范。
- 使用一致的空白符將代碼分隔成塊,這樣利于掃描較大的文檔。
- 如果使用了多個 CSS 文件,將其按照組件而非頁面的形式分拆,因為頁面會被重組,而組件只會被移動。
/* * Component section heading */ .element { ... } /* * Component section heading * * Sometimes you need to include optional context for the entire component. Do that up here if it's important enough. */ .element { ... } /* Contextual sub-component or modifer */ .element-heading { ... }
編輯器配置
- 將你的編輯器按照下面的配置進行設置,以避免常見的代碼不一致和差異:
- 用兩個空格代替制表符(soft-tab 即用空格代表 tab 符)。
- 保存文件時,刪除尾部的空白符。
- 設置文件編碼為 UTF-8。
- 在文件結尾添加一個空白行。
來源網絡,侵權聯系刪除
為工作中經常用到這些方法,所有便把這些方法進行了總結。
isString (o) { //是否字符串
return Object.prototype.toString.call(o).slice(8, -1)==='String'
}
isNumber (o) { //是否數字
return Object.prototype.toString.call(o).slice(8, -1)==='Number'
}
isBoolean (o) { //是否boolean
return Object.prototype.toString.call(o).slice(8, -1)==='Boolean'
}
isFunction (o) { //是否函數
return Object.prototype.toString.call(o).slice(8, -1)==='Function'
}
isNull (o) { //是否為null
return Object.prototype.toString.call(o).slice(8, -1)==='Null'
}
isUndefined (o) { //是否undefined
return Object.prototype.toString.call(o).slice(8, -1)==='Undefined'
}
isObj (o) { //是否對象
return Object.prototype.toString.call(o).slice(8, -1)==='Object'
}
isArray (o) { //是否數組
return Object.prototype.toString.call(o).slice(8, -1)==='Array'
}
isDate (o) { //是否時間
return Object.prototype.toString.call(o).slice(8, -1)==='Date'
}
isRegExp (o) { //是否正則
return Object.prototype.toString.call(o).slice(8, -1)==='RegExp'
}
isError (o) { //是否錯誤對象
return Object.prototype.toString.call(o).slice(8, -1)==='Error'
}
isSymbol (o) { //是否Symbol函數
return Object.prototype.toString.call(o).slice(8, -1)==='Symbol'
}
isPromise (o) { //是否Promise對象
return Object.prototype.toString.call(o).slice(8, -1)==='Promise'
}
isSet (o) { //是否Set對象
return Object.prototype.toString.call(o).slice(8, -1)==='Set'
}
isFalse (o) {
if (!o || o==='null' || o==='undefined' || o==='false' || o==='NaN') return true
return false
}
isTrue (o) {
return !this.isFalse(o)
}
isIos () {
var u=navigator.userAgent;
if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {//安卓手機
// return "Android";
return false
} else if (u.indexOf('iPhone') > -1) {//蘋果手機
// return "iPhone";
return true
} else if (u.indexOf('iPad') > -1) {//iPad
// return "iPad";
return false
} else if (u.indexOf('Windows Phone') > -1) {//winphone手機
// return "Windows Phone";
return false
}else{
return false
}
}
isPC () { //是否為PC端
var userAgentInfo=navigator.userAgent;
var Agents=["Android", "iPhone",
"SymbianOS", "Windows Phone",
"iPad", "iPod"];
var flag=true;
for (var v=0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) {
flag=false;
break;
}
}
return flag;
}
browserType(){
var userAgent=navigator.userAgent; //取得瀏覽器的userAgent字符串
var isOpera=userAgent.indexOf("Opera") > -1; //判斷是否Opera瀏覽器
var isIE=userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判斷是否IE瀏覽器
var isIE11=userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
var isEdge=userAgent.indexOf("Edge") > -1 && !isIE; //判斷是否IE的Edge瀏覽器
var isFF=userAgent.indexOf("Firefox") > -1; //判斷是否Firefox瀏覽器
var isSafari=userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome")==-1; //判斷是否Safari瀏覽器
var isChrome=userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //判斷Chrome瀏覽器
if (isIE) {
var reIE=new RegExp("MSIE (\\d+\\.\\d+);");
reIE.test(userAgent);
var fIEVersion=parseFloat(RegExp["$1"]);
if(fIEVersion==7) return "IE7"
else if(fIEVersion==8) return "IE8";
else if(fIEVersion==9) return "IE9";
else if(fIEVersion==10) return "IE10";
else return "IE7以下"//IE版本過低
}
if (isIE11) return 'IE11';
if (isEdge) return "Edge";
if (isFF) return "FF";
if (isOpera) return "Opera";
if (isSafari) return "Safari";
if (isChrome) return "Chrome";
}
checkStr (str, type) {
switch (type) {
case 'phone': //手機號碼
return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
case 'tel': //座機
return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
case 'card': //身份證
return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
case 'pwd': //密碼以字母開頭,長度在6~18之間,只能包含字母、數字和下劃線
return /^[a-zA-Z]\w{5,17}$/.test(str)
case 'postal': //郵政編碼
return /[1-9]\d{5}(?!\d)/.test(str);
case 'QQ': //QQ號
return /^[1-9][0-9]{4,9}$/.test(str);
case 'email': //郵箱
return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
case 'money': //金額(小數點2位)
return /^\d*(?:\.\d{0,2})?$/.test(str);
case 'URL': //網址
return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
case 'IP': //IP
return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
case 'date': //日期時間
return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
case 'number': //數字
return /^[0-9]$/.test(str);
case 'english': //英文
return /^[a-zA-Z]+$/.test(str);
case 'chinese': //中文
return /^[\u4E00-\u9FA5]+$/.test(str);
case 'lower': //小寫
return /^[a-z]+$/.test(str);
case 'upper': //大寫
return /^[A-Z]+$/.test(str);
case 'HTML': //HTML標記
return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
default:
return true;
}
// 嚴格的身份證校驗
isCardID(sId) {
if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(sId)) {
alert('你輸入的身份證長度或格式錯誤')
return false
}
//身份證城市
var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"內蒙古",21:"遼寧",22:"吉林",23:"黑龍江",31:"上海",32:"江蘇",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山東",41:"河南",42:"湖北",43:"湖南",44:"廣東",45:"廣西",46:"海南",50:"重慶",51:"四川",52:"貴州",53:"云南",54:"西藏",61:"陜西",62:"甘肅",63:"青海",64:"寧夏",65:"新疆",71:"臺灣",81:"香港",82:"澳門",91:"國外"};
if(!aCity[parseInt(sId.substr(0,2))]) {
alert('你的身份證地區非法')
return false
}
// 出生日期驗證
var sBirthday=(sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2))).replace(/-/g,"/"),
d=new Date(sBirthday)
if(sBirthday !=(d.getFullYear()+"/"+ (d.getMonth()+1) + "/" + d.getDate())) {
alert('身份證上的出生日期非法')
return false
}
// 身份證號碼校驗
var sum=0,
weights=[7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
codes="10X98765432"
for (var i=0; i < sId.length - 1; i++) {
sum +=sId[i] * weights[i];
}
var last=codes[sum % 11]; //計算出來的最后一位身份證號碼
if (sId[sId.length-1] !=last) {
alert('你輸入的身份證號非法')
return false
}
return true
}
}
/**
* 格式化時間
*
* @param {time} 時間
* @param {cFormat} 格式
* @return {String} 字符串
*
* @example formatTime('2018-1-29', '{y}/{m}/blxzbzf {h}:{i}:{s}') // -> 2018/01/29 00:00:00
*/
formatTime(time, cFormat) {
if (arguments.length===0) return null
if ((time + '').length===10) {
time=+time * 1000
}
var format=cFormat || '{y}-{m}-dxjtxvt {h}:{i}:{s}', date
if (typeof time==='object') {
date=time
} else {
date=new Date(time)
}
var formatObj={
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
var time_str=format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key)=> {
var value=formatObj[key]
if (key==='a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
if (result.length > 0 && value < 10) {
value='0' + value
}
return value || 0
})
return time_str
}
/**
* 返回指定長度的月份集合
*
* @param {time} 時間
* @param {len} 長度
* @param {direction} 方向: 1: 前幾個月; 2: 后幾個月; 3:前后幾個月 默認 3
* @return {Array} 數組
*
* @example getMonths('2018-1-29', 6, 1) // -> ["2018-1", "2017-12", "2017-11", "2017-10", "2017-9", "2017-8", "2017-7"]
*/
getMonths(time, len, direction) {
var mm=new Date(time).getMonth(),
yy=new Date(time).getFullYear(),
direction=isNaN(direction) ? 3 : direction,
index=mm;
var cutMonth=function(index) {
if ( index <=len && index >=-len) {
return direction===1 ? formatPre(index).concat(cutMonth(++index)):
direction===2 ? formatNext(index).concat(cutMonth(++index)):formatCurr(index).concat(cutMonth(++index))
}
return []
}
var formatNext=function(i) {
var y=Math.floor(i/12),
m=i%12
return [yy+y + '-' + (m+1)]
}
var formatPre=function(i) {
var y=Math.ceil(i/12),
m=i%12
m=m===0 ? 12 : m
return [yy-y + '-' + (13 - m)]
}
var formatCurr=function(i) {
var y=Math.floor(i/12),
yNext=Math.ceil(i/12),
m=i%12,
mNext=m===0 ? 12 : m
return [yy-yNext + '-' + (13 - mNext),yy+y + '-' + (m+1)]
}
// 數組去重
var unique=function(arr) {
if ( Array.hasOwnProperty('from') ) {
return Array.from(new Set(arr));
}else{
var n={},r=[];
for(var i=0; i < arr.length; i++){
if (!n[arr[i]]){
n[arr[i]]=true;
r.push(arr[i]);
}
}
return r;
}
}
return direction !==3 ? cutMonth(index) : unique(cutMonth(index).sort(function(t1, t2){
return new Date(t1).getTime() - new Date(t2).getTime()
}))
}
/**
* 返回指定長度的天數集合
*
* @param {time} 時間
* @param {len} 長度
* @param {direction} 方向: 1: 前幾天; 2: 后幾天; 3:前后幾天 默認 3
* @return {Array} 數組
*
* @example date.getDays('2018-1-29', 6) // -> ["2018-1-26", "2018-1-27", "2018-1-28", "2018-1-29", "2018-1-30", "2018-1-31", "2018-2-1"]
*/
getDays(time, len, diretion) {
var tt=new Date(time)
var getDay=function(day) {
var t=new Date(time)
t.setDate(t.getDate() + day)
var m=t.getMonth()+1
return t.getFullYear()+'-'+m+'-'+t.getDate()
}
var arr=[]
if (diretion===1) {
for (var i=1; i <=len; i++) {
arr.unshift(getDay(-i))
}
}else if(diretion===2) {
for (var i=1; i <=len; i++) {
arr.push(getDay(i))
}
}else {
for (var i=1; i <=len; i++) {
arr.unshift(getDay(-i))
}
arr.push(tt.getFullYear()+'-'+(tt.getMonth()+1)+'-'+tt.getDate())
for (var i=1; i <=len; i++) {
arr.push(getDay(i))
}
}
return diretion===1 ? arr.concat([tt.getFullYear()+'-'+(tt.getMonth()+1)+'-'+tt.getDate()]) :
diretion===2 ? [tt.getFullYear()+'-'+(tt.getMonth()+1)+'-'+tt.getDate()].concat(arr) : arr
}
/**
* @param {s} 秒數
* @return {String} 字符串
*
* @example formatHMS(3610) // -> 1h0m10s
*/
formatHMS (s) {
var str=''
if (s > 3600) {
str=Math.floor(s/3600)+'h'+Math.floor(s%3600/60)+'m'+s%60+'s'
}else if(s > 60) {
str=Math.floor(s/60)+'m'+s%60+'s'
}else{
str=s%60+'s'
}
return str
}
/*獲取某月有多少天*/
getMonthOfDay (time) {
var date=new Date(time)
var year=date.getFullYear()
var mouth=date.getMonth() + 1
var days
//當月份為二月時,根據閏年還是非閏年判斷天數
if (mouth==2) {
days=(year%4==0 && year%100==0 && year%400==0) || (year%4==0 && year%100!=0) ? 28 : 29
} else if (mouth==1 || mouth==3 || mouth==5 || mouth==7 || mouth==8 || mouth==10 || mouth==12) {
//月份為:1,3,5,7,8,10,12 時,為大月.則天數為31;
days=31
} else {
//其他月份,天數為:30.
days=30
}
return days
}
/*獲取某年有多少天*/
getYearOfDay (time) {
var firstDayYear=this.getFirstDayOfYear(time);
var lastDayYear=this.getLastDayOfYear(time);
var numSecond=(new Date(lastDayYear).getTime() - new Date(firstDayYear).getTime())/1000;
return Math.ceil(numSecond/(24*3600));
}
/*獲取某年的第一天*/
getFirstDayOfYear (time) {
var year=new Date(time).getFullYear();
return year + "-01-01 00:00:00";
}
/*獲取某年最后一天*/
getLastDayOfYear (time) {
var year=new Date(time).getFullYear();
var dateString=year + "-12-01 00:00:00";
var endDay=this.getMonthOfDay(dateString);
return year + "-12-" + endDay + " 23:59:59";
}
/*獲取某個日期是當年中的第幾天*/
getDayOfYear (time) {
var firstDayYear=this.getFirstDayOfYear(time);
var numSecond=(new Date(time).getTime() - new Date(firstDayYear).getTime())/1000;
return Math.ceil(numSecond/(24*3600));
}
/*獲取某個日期在這一年的第幾周*/
getDayOfYearWeek (time) {
var numdays=this.getDayOfYear(time);
return Math.ceil(numdays / 7);
}
/*判斷一個元素是否在數組中*/
contains (arr, val) {
return arr.indexOf(val) !=-1 ? true : false;
}
/**
* @param {arr} 數組
* @param {fn} 回調函數
* @return {undefined}
*/
each (arr, fn) {
fn=fn || Function;
var a=[];
var args=Array.prototype.slice.call(arguments, 1);
for(var i=0; i < arr.length; i++) {
var res=fn.apply(arr, [arr[i], i].concat(args));
if(res !=null) a.push(res);
}
}
/**
* @param {arr} 數組
* @param {fn} 回調函數
* @param {thisObj} this指向
* @return {Array}
*/
map (arr, fn, thisObj) {
var scope=thisObj || window;
var a=[];
for(var i=0, j=arr.length; i < j; ++i) {
var res=fn.call(scope, arr[i], i, this);
if(res !=null) a.push(res);
}
return a;
}
/**
* @param {arr} 數組
* @param {type} 1:從小到大 2:從大到小 3:隨機
* @return {Array}
*/
sort (arr, type=1) {
return arr.sort( (a, b)=> {
switch(type) {
case 1:
return a - b;
case 2:
return b - a;
case 3:
return Math.random() - 0.5;
default:
return arr;
}
})
}
/*去重*/
unique (arr) {
if ( Array.hasOwnProperty('from') ) {
return Array.from(new Set(arr));
}else{
var n={},r=[];
for(var i=0; i < arr.length; i++){
if (!n[arr[i]]){
n[arr[i]]=true;
r.push(arr[i]);
}
}
return r;
}
// 注:上面 else 里面的排重并不能區分 2 和 '2',但能減少用indexOf帶來的性能,暫時沒找到替代的方法。。。
/* 正確排重
if ( Array.hasOwnProperty('from') ) {
return Array.from(new Set(arr))
}else{
var r=[], NaNBol=true
for(var i=0; i < arr.length; i++) {
if (arr[i] !==arr[i]) {
if (NaNBol && r.indexOf(arr[i])===-1) {
r.push(arr[i])
NaNBol=false
}
}else{
if(r.indexOf(arr[i])===-1) r.push(arr[i])
}
}
return r
}
*/
}
/*求兩個集合的并集*/
union (a, b) {
var newArr=a.concat(b);
return this.unique(newArr);
}
/*求兩個集合的交集*/
intersect (a, b) {
var _this=this;
a=this.unique(a);
return this.map(a, function(o) {
return _this.contains(b, o) ? o : null;
});
}
/*刪除其中一個元素*/
remove (arr, ele) {
var index=arr.indexOf(ele);
if(index > -1) {
arr.splice(index, 1);
}
return arr;
}
/*將類數組轉換為數組的方法*/
formArray (ary) {
var arr=[];
if(Array.isArray(ary)) {
arr=ary;
} else {
arr=Array.prototype.slice.call(ary);
};
return arr;
}
/*最大值*/
max (arr) {
return Math.max.apply(null, arr);
}
/*最小值*/
min (arr) {
return Math.min.apply(null, arr);
}
/*求和*/
sum (arr) {
return arr.reduce( (pre, cur)=> {
return pre + cur
})
}
/*平均值*/
average (arr) {
return this.sum(arr)/arr.length
}
/**
* 去除空格
* @param {str}
* @param {type}
* type: 1-所有空格 2-前后空格 3-前空格 4-后空格
* @return {String}
*/
trim (str, type) {
type=type || 1
switch (type) {
case 1:
return str.replace(/\s+/g, "");
case 2:
return str.replace(/(^\s*)|(\s*$)/g, "");
case 3:
return str.replace(/(^\s*)/g, "");
case 4:
return str.replace(/(\s*$)/g, "");
default:
return str;
}
}
/**
* @param {str}
* @param {type}
* type: 1:首字母大寫 2:首頁母小寫 3:大小寫轉換 4:全部大寫 5:全部小寫
* @return {String}
*/
changeCase (str, type) {
type=type || 4
switch (type) {
case 1:
return str.replace(/\b\w+\b/g, function (word) {
return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
});
case 2:
return str.replace(/\b\w+\b/g, function (word) {
return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase();
});
case 3:
return str.split('').map( function(word){
if (/[a-z]/.test(word)) {
return word.toUpperCase();
}else{
return word.toLowerCase()
}
}).join('')
case 4:
return str.toUpperCase();
case 5:
return str.toLowerCase();
default:
return str;
}
}
/*
檢測密碼強度
*/
checkPwd (str) {
var Lv=0;
if (str.length < 6) {
return Lv
}
if (/[0-9]/.test(str)) {
Lv++
}
if (/[a-z]/.test(str)) {
Lv++
}
if (/[A-Z]/.test(str)) {
Lv++
}
if (/[\.|-|_]/.test(str)) {
Lv++
}
return Lv;
}
/*過濾html代碼(把<>轉換)*/
filterTag (str) {
str=str.replace(/&/ig, "&");
str=str.replace(/</ig, "<");
str=str.replace(/>/ig, ">");
str=str.replace(" ", " ");
return str;
}
/*隨機數范圍*/
random (min, max) {
if (arguments.length===2) {
return Math.floor(min + Math.random() * ( (max+1) - min ))
}else{
return null;
}
}
/*將阿拉伯數字翻譯成中文的大寫數字*/
numberToChinese (num) {
var AA=new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十");
var BB=new Array("", "十", "百", "仟", "萬", "億", "點", "");
var a=("" + num).replace(/(^0*)/g, "").split("."),
k=0,
re="";
for(var i=a[0].length - 1; i >=0; i--) {
switch(k) {
case 0:
re=BB[7] + re;
break;
case 4:
if(!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$")
.test(a[0]))
re=BB[4] + re;
break;
case 8:
re=BB[5] + re;
BB[7]=BB[5];
k=0;
break;
}
if(k % 4==2 && a[0].charAt(i + 2) !=0 && a[0].charAt(i + 1)==0)
re=AA[0] + re;
if(a[0].charAt(i) !=0)
re=AA[a[0].charAt(i)] + BB[k % 4] + re;
k++;
}
if(a.length > 1) // 加上小數部分(如果有小數部分)
{
re +=BB[6];
for(var i=0; i < a[1].length; i++)
re +=AA[a[1].charAt(i)];
}
if(re=='一十')
re="十";
if(re.match(/^一/) && re.length==3)
re=re.replace("一", "");
return re;
}
/*將數字轉換為大寫金額*/
changeToChinese (Num) {
//判斷如果傳遞進來的不是字符的話轉換為字符
if(typeof Num=="number") {
Num=new String(Num);
};
Num=Num.replace(/,/g, "") //替換tomoney()中的“,”
Num=Num.replace(/ /g, "") //替換tomoney()中的空格
Num=Num.replace(/¥/g, "") //替換掉可能出現的¥字符
if(isNaN(Num)) { //驗證輸入的字符是否為數字
//alert("請檢查小寫金額是否正確");
return "";
};
//字符處理完畢后開始轉換,采用前后兩部分分別轉換
var part=String(Num).split(".");
var newchar="";
//小數點前進行轉化
for(var i=part[0].length - 1; i >=0; i--) {
if(part[0].length > 10) {
return "";
//若數量超過拾億單位,提示
}
var tmpnewchar=""
var perchar=part[0].charAt(i);
switch(perchar) {
case "0":
tmpnewchar="零" + tmpnewchar;
break;
case "1":
tmpnewchar="壹" + tmpnewchar;
break;
case "2":
tmpnewchar="貳" + tmpnewchar;
break;
case "3":
tmpnewchar="叁" + tmpnewchar;
break;
case "4":
tmpnewchar="肆" + tmpnewchar;
break;
case "5":
tmpnewchar="伍" + tmpnewchar;
break;
case "6":
tmpnewchar="陸" + tmpnewchar;
break;
case "7":
tmpnewchar="柒" + tmpnewchar;
break;
case "8":
tmpnewchar="捌" + tmpnewchar;
break;
case "9":
tmpnewchar="玖" + tmpnewchar;
break;
}
switch(part[0].length - i - 1) {
case 0:
tmpnewchar=tmpnewchar + "元";
break;
case 1:
if(perchar !=0) tmpnewchar=tmpnewchar + "拾";
break;
case 2:
if(perchar !=0) tmpnewchar=tmpnewchar + "佰";
break;
case 3:
if(perchar !=0) tmpnewchar=tmpnewchar + "仟";
break;
case 4:
tmpnewchar=tmpnewchar + "萬";
break;
case 5:
if(perchar !=0) tmpnewchar=tmpnewchar + "拾";
break;
case 6:
if(perchar !=0) tmpnewchar=tmpnewchar + "佰";
break;
case 7:
if(perchar !=0) tmpnewchar=tmpnewchar + "仟";
break;
case 8:
tmpnewchar=tmpnewchar + "億";
break;
case 9:
tmpnewchar=tmpnewchar + "拾";
break;
}
var newchar=tmpnewchar + newchar;
}
//小數點之后進行轉化
if(Num.indexOf(".") !=-1) {
if(part[1].length > 2) {
// alert("小數點之后只能保留兩位,系統將自動截斷");
part[1]=part[1].substr(0, 2)
}
for(i=0; i < part[1].length; i++) {
tmpnewchar=""
perchar=part[1].charAt(i)
switch(perchar) {
case "0":
tmpnewchar="零" + tmpnewchar;
break;
case "1":
tmpnewchar="壹" + tmpnewchar;
break;
case "2":
tmpnewchar="貳" + tmpnewchar;
break;
case "3":
tmpnewchar="叁" + tmpnewchar;
break;
case "4":
tmpnewchar="肆" + tmpnewchar;
break;
case "5":
tmpnewchar="伍" + tmpnewchar;
break;
case "6":
tmpnewchar="陸" + tmpnewchar;
break;
case "7":
tmpnewchar="柒" + tmpnewchar;
break;
case "8":
tmpnewchar="捌" + tmpnewchar;
break;
case "9":
tmpnewchar="玖" + tmpnewchar;
break;
}
if(i==0) tmpnewchar=tmpnewchar + "角";
if(i==1) tmpnewchar=tmpnewchar + "分";
newchar=newchar + tmpnewchar;
}
}
//替換所有無用漢字
while(newchar.search("零零") !=-1)
newchar=newchar.replace("零零", "零");
newchar=newchar.replace("零億", "億");
newchar=newchar.replace("億萬", "億");
newchar=newchar.replace("零萬", "萬");
newchar=newchar.replace("零元", "元");
newchar=newchar.replace("零角", "");
newchar=newchar.replace("零分", "");
if(newchar.charAt(newchar.length - 1)=="元") {
newchar=newchar + "整"
}
return newchar;
}
/**
* @param {setting}
*/
ajax(setting){
//設置參數的初始值
var opts={
method: (setting.method || "GET").toUpperCase(), //請求方式
url: setting.url || "", // 請求地址
async: setting.async || true, // 是否異步
dataType: setting.dataType || "json", // 解析方式
data: setting.data || "", // 參數
success: setting.success || function(){}, // 請求成功回調
error: setting.error || function(){} // 請求失敗回調
}
// 參數格式化
function params_format (obj) {
var str=''
for (var i in obj) {
str +=i + '=' + obj[i] + '&'
}
return str.split('').slice(0, -1).join('')
}
// 創建ajax對象
var xhr=new XMLHttpRequest();
// 連接服務器open(方法GET/POST,請求地址, 異步傳輸)
if(opts.method=='GET'){
xhr.open(opts.method, opts.url + "?" + params_format(opts.data), opts.async);
xhr.send();
}else{
xhr.open(opts.method, opts.url, opts.async);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(opts.data);
}
/*
** 每當readyState改變時,就會觸發onreadystatechange事件
** readyState屬性存儲有XMLHttpRequest的狀態信息
** 0 :請求未初始化
** 1 :服務器連接已建立
** 2 :請求已接受
** 3 : 請求處理中
** 4 :請求已完成,且相應就緒
*/
xhr.onreadystatechange=function() {
if (xhr.readyState===4 && (xhr.status===200 || xhr.status===304)) {
switch(opts.dataType){
case "json":
var json=JSON.parse(xhr.responseText);
opts.success(json);
break;
case "xml":
opts.success(xhr.responseXML);
break;
default:
opts.success(xhr.responseText);
break;
}
}
}
xhr.onerror=function(err) {
opts.error(err);
}
}
/**
* @param {url}
* @param {setting}
* @return {Promise}
*/
fetch(url, setting) {
//設置參數的初始值
let opts={
method: (setting.method || 'GET').toUpperCase(), //請求方式
headers : setting.headers || {}, // 請求頭設置
credentials : setting.credentials || true, // 設置cookie是否一起發送
body: setting.body || {},
mode : setting.mode || 'no-cors', // 可以設置 cors, no-cors, same-origin
redirect : setting.redirect || 'follow', // follow, error, manual
cache : setting.cache || 'default' // 設置 cache 模式 (default, reload, no-cache)
}
let dataType=setting.dataType || "json", // 解析方式
data=setting.data || "" // 參數
// 參數格式化
function params_format (obj) {
var str=''
for (var i in obj) {
str +=`${i}=${obj[i]}&`
}
return str.split('').slice(0, -1).join('')
}
if (opts.method==='GET') {
url=url + (data?`?${params_format(data)}`:'')
}else{
setting.body=data || {}
}
return new Promise( (resolve, reject)=> {
fetch(url, opts).then( async res=> {
let data=dataType==='text' ? await res.text() :
dataType==='blob' ? await res.blob() : await res.json()
resolve(data)
}).catch( e=> {
reject(e)
})
})
}
$ (selector){
var type=selector.substring(0, 1);
if (type==='#') {
if (document.querySelecotor) return document.querySelector(selector)
return document.getElementById(selector.substring(1))
}else if (type==='.') {
if (document.querySelecotorAll) return document.querySelectorAll(selector)
return document.getElementsByClassName(selector.substring(1))
}else{
return document['querySelectorAll' ? 'querySelectorAll':'getElementsByTagName'](selector)
}
}
/*檢測類名*/
hasClass (ele, name) {
return ele.className.match(new RegExp('(\\s|^)' + name + '(\\s|$)'));
}
/*添加類名*/
addClass (ele, name) {
if (!this.hasClass(ele, name)) ele.className +=" " + name;
}
/*刪除類名*/
removeClass (ele, name) {
if (this.hasClass(ele, name)) {
var reg=new RegExp('(\\s|^)' + name + '(\\s|$)');
ele.className=ele.className.replace(reg, '');
}
}
/*替換類名*/
replaceClass (ele, newName, oldName) {
this.removeClass(ele, oldName);
this.addClass(ele, newName);
}
/*獲取兄弟節點*/
siblings (ele) {
console.log(ele.parentNode)
var chid=ele.parentNode.children,eleMatch=[];
for(var i=0, len=chid.length; i < len; i ++){
if(chid[i] !=ele){
eleMatch.push(chid[i]);
}
}
return eleMatch;
}
/*獲取行間樣式屬性*/
getByStyle (obj,name){
if(obj.currentStyle){
return obj.currentStyle[name];
}else{
return getComputedStyle(obj,false)[name];
}
}
class StorageFn {
constructor () {
this.ls=window.localStorage;
this.ss=window.sessionStorage;
}
/*-----------------cookie---------------------*/
/*設置cookie*/
setCookie (name, value, day) {
var setting=arguments[0];
if (Object.prototype.toString.call(setting).slice(8, -1)==='Object'){
for (var i in setting) {
var oDate=new Date();
oDate.setDate(oDate.getDate() + day);
document.cookie=i + '=' + setting[i] + ';expires=' + oDate;
}
}else{
var oDate=new Date();
oDate.setDate(oDate.getDate() + day);
document.cookie=name + '=' + value + ';expires=' + oDate;
}
}
/*獲取cookie*/
getCookie (name) {
var arr=document.cookie.split('; ');
for (var i=0; i < arr.length; i++) {
var arr2=arr[i].split('=');
if (arr2[0]==name) {
return arr2[1];
}
}
return '';
}
/*刪除cookie*/
removeCookie (name) {
this.setCookie(name, 1, -1);
}
/*-----------------localStorage---------------------*/
/*設置localStorage*/
setLocal(key, val) {
var setting=arguments[0];
if (Object.prototype.toString.call(setting).slice(8, -1)==='Object'){
for(var i in setting){
this.ls.setItem(i, JSON.stringify(setting[i]))
}
}else{
this.ls.setItem(key, JSON.stringify(val))
}
}
/*獲取localStorage*/
getLocal(key) {
if (key) return JSON.parse(this.ls.getItem(key))
return null;
}
/*移除localStorage*/
removeLocal(key) {
this.ls.removeItem(key)
}
/*移除所有localStorage*/
clearLocal() {
this.ls.clear()
}
/*-----------------sessionStorage---------------------*/
/*設置sessionStorage*/
setSession(key, val) {
var setting=arguments[0];
if (Object.prototype.toString.call(setting).slice(8, -1)==='Object'){
for(var i in setting){
this.ss.setItem(i, JSON.stringify(setting[i]))
}
}else{
this.ss.setItem(key, JSON.stringify(val))
}
}
/*獲取sessionStorage*/
getSession(key) {
if (key) return JSON.parse(this.ss.getItem(key))
return null;
}
/*移除sessionStorage*/
removeSession(key) {
this.ss.removeItem(key)
}
/*移除所有sessionStorage*/
clearSession() {
this.ss.clear()
}
}
/*獲取網址參數*/
getURL(name){
var reg=new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r=decodeURI(window.location.search).substr(1).match(reg);
if(r!=null) return r[2]; return null;
}
/*獲取全部url參數,并轉換成json對象*/
getUrlAllParams (url) {
var url=url ? url : window.location.href;
var _pa=url.substring(url.indexOf('?') + 1),
_arrS=_pa.split('&'),
_rs={};
for (var i=0, _len=_arrS.length; i < _len; i++) {
var pos=_arrS[i].indexOf('=');
if (pos==-1) {
continue;
}
var name=_arrS[i].substring(0, pos),
value=window.decodeURIComponent(_arrS[i].substring(pos + 1));
_rs[name]=value;
}
return _rs;
}
/*刪除url指定參數,返回url*/
delParamsUrl(url, name){
var baseUrl=url.split('?')[0] + '?';
var query=url.split('?')[1];
if (query.indexOf(name)>-1) {
var obj={}
var arr=query.split("&");
for (var i=0; i < arr.length; i++) {
arr[i]=arr[i].split("=");
obj[arr[i][0]]=arr[i][1];
};
delete obj[name];
var url=baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&");
return url
}else{
return url;
}
}
/*獲取十六進制隨機顏色*/
getRandomColor () {
return '#' + (function(h) {
return new Array(7 - h.length).join("0") + h;
})((Math.random() * 0x1000000 << 0).toString(16));
}
/*圖片加載*/
imgLoadAll(arr,callback){
var arrImg=[];
for (var i=0; i < arr.length; i++) {
var img=new Image();
img.src=arr[i];
img.onload=function(){
arrImg.push(this);
if (arrImg.length==arr.length) {
callback && callback();
}
}
}
}
/*音頻加載*/
loadAudio(src, callback) {
var audio=new Audio(src);
audio.onloadedmetadata=callback;
audio.src=src;
}
/*DOM轉字符串*/
domToStirng(htmlDOM){
var div=document.createElement("div");
div.appendChild(htmlDOM);
return div.innerHTML
}
/*字符串轉DOM*/
stringToDom(htmlString){
var div=document.createElement("div");
div.innerHTML=htmlString;
return div.children[0];
}
/**
* 光標所在位置插入字符,并設置光標位置
*
* @param {dom} 輸入框
* @param {val} 插入的值
* @param {posLen} 光標位置處在 插入的值的哪個位置
*/
setCursorPosition (dom,val,posLen) {
var cursorPosition=0;
if(dom.selectionStart){
cursorPosition=dom.selectionStart;
}
this.insertAtCursor(dom,val);
dom.focus();
console.log(posLen)
dom.setSelectionRange(dom.value.length,cursorPosition + (posLen || val.length));
}
/*光標所在位置插入字符*/
insertAtCursor(dom, val) {
if (document.selection){
dom.focus();
sel=document.selection.createRange();
sel.text=val;
sel.select();
}else if (dom.selectionStart || dom.selectionStart=='0'){
let startPos=dom.selectionStart;
let endPos=dom.selectionEnd;
let restoreTop=dom.scrollTop;
dom.value=dom.value.substring(0, startPos) + val + dom.value.substring(endPos, dom.value.length);
if (restoreTop > 0){
dom.scrollTop=restoreTop;
}
dom.focus();
dom.selectionStart=startPos + val.length;
dom.selectionEnd=startPos + val.length;
} else {
dom.value +=val;
dom.focus();
}
}
/* normalize.css */
html {
line-height: 1.15;
/* 1 */
-ms-text-size-adjust: 100%;
/* 2 */
-webkit-text-size-adjust: 100%;
/* 2 */
}
body {
margin: 0;
}
article,
aside,
footer,
header,
nav,
section {
display: block;
}
h1 {
font-size: 2em;
margin: 0.67em 0;
}
figcaption,
figure,
main {
/* 1 */
display: block;
}
figure {
margin: 1em 40px;
}
hr {
box-sizing: content-box;
/* 1 */
height: 0;
/* 1 */
overflow: visible;
/* 2 */
}
pre {
font-family: monospace, monospace;
/* 1 */
font-size: 1em;
/* 2 */
}
a {
background-color: transparent;
/* 1 */
-webkit-text-decoration-skip: objects;
/* 2 */
}
abbr[title] {
border-bottom: none;
/* 1 */
text-decoration: underline;
/* 2 */
text-decoration: underline dotted;
/* 2 */
}
b,
strong {
font-weight: inherit;
}
b,
strong {
font-weight: bolder;
}
code,
kbd,
samp {
font-family: monospace, monospace;
/* 1 */
font-size: 1em;
/* 2 */
}
dfn {
font-style: italic;
}
mark {
background-color: #ff0;
color: #000;
}
small {
font-size: 80%;
}
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
audio,
video {
display: inline-block;
}
audio:not([controls]) {
display: none;
height: 0;
}
img {
border-style: none;
}
svg:not(:root) {
overflow: hidden;
}
button,
input,
optgroup,
select,
textarea {
font-family: sans-serif;
/* 1 */
font-size: 100%;
/* 1 */
line-height: 1.15;
/* 1 */
margin: 0;
/* 2 */
}
button,
input {
/* 1 */
overflow: visible;
}
button,
select {
/* 1 */
text-transform: none;
}
button,
html [type="button"],
/* 1 */
[type="reset"],
[type="submit"] {
-webkit-appearance: button;
/* 2 */
}
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0;
}
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: 1px dotted ButtonText;
}
fieldset {
padding: 0.35em 0.75em 0.625em;
}
legend {
box-sizing: border-box;
/* 1 */
color: inherit;
/* 2 */
display: table;
/* 1 */
max-width: 100%;
/* 1 */
padding: 0;
/* 3 */
white-space: normal;
/* 1 */
}
progress {
display: inline-block;
/* 1 */
vertical-align: baseline;
/* 2 */
}
textarea {
overflow: auto;
}
[type="checkbox"],
[type="radio"] {
box-sizing: border-box;
/* 1 */
padding: 0;
/* 2 */
}
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
[type="search"] {
-webkit-appearance: textfield;
/* 1 */
outline-offset: -2px;
/* 2 */
}
[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-file-upload-button {
-webkit-appearance: button;
/* 1 */
font: inherit;
/* 2 */
}
details,
/* 1 */
menu {
display: block;
}
summary {
display: list-item;
}
canvas {
display: inline-block;
}
template {
display: none;
}
[hidden] {
display: none;
}
/* reset */
html,
body,
h1,
h2,
h3,
h4,
h5,
h6,
div,
dl,
dt,
dd,
ul,
ol,
li,
p,
blockquote,
pre,
hr,
figure,
table,
caption,
th,
td,
form,
fieldset,
legend,
input,
button,
textarea,
menu {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* normalize.css */
html {
line-height: 1.15;
/* 1 */
-ms-text-size-adjust: 100%;
/* 2 */
-webkit-text-size-adjust: 100%;
/* 2 */
}
body {
margin: 0;
}
article,
aside,
footer,
header,
nav,
section {
display: block;
}
h1 {
font-size: 2em;
margin: 0.67em 0;
}
figcaption,
figure,
main {
/* 1 */
display: block;
}
figure {
margin: 1em 40px;
}
hr {
box-sizing: content-box;
/* 1 */
height: 0;
/* 1 */
overflow: visible;
/* 2 */
}
pre {
font-family: monospace, monospace;
/* 1 */
font-size: 1em;
/* 2 */
}
a {
background-color: transparent;
/* 1 */
-webkit-text-decoration-skip: objects;
/* 2 */
}
abbr[title] {
border-bottom: none;
/* 1 */
text-decoration: underline;
/* 2 */
text-decoration: underline dotted;
/* 2 */
}
b,
strong {
font-weight: inherit;
}
b,
strong {
font-weight: bolder;
}
code,
kbd,
samp {
font-family: monospace, monospace;
/* 1 */
font-size: 1em;
/* 2 */
}
dfn {
font-style: italic;
}
mark {
background-color: #ff0;
color: #000;
}
small {
font-size: 80%;
}
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
audio,
video {
display: inline-block;
}
audio:not([controls]) {
display: none;
height: 0;
}
img {
border-style: none;
}
svg:not(:root) {
overflow: hidden;
}
button,
input,
optgroup,
select,
textarea {
font-family: sans-serif;
/* 1 */
font-size: 100%;
/* 1 */
line-height: 1.15;
/* 1 */
margin: 0;
/* 2 */
}
button,
input {
/* 1 */
overflow: visible;
}
button,
select {
/* 1 */
text-transform: none;
}
button,
html [type="button"],
/* 1 */
[type="reset"],
[type="submit"] {
-webkit-appearance: button;
/* 2 */
}
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0;
}
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: 1px dotted ButtonText;
}
fieldset {
padding: 0.35em 0.75em 0.625em;
}
legend {
box-sizing: border-box;
/* 1 */
color: inherit;
/* 2 */
display: table;
/* 1 */
max-width: 100%;
/* 1 */
padding: 0;
/* 3 */
white-space: normal;
/* 1 */
}
progress {
display: inline-block;
/* 1 */
vertical-align: baseline;
/* 2 */
}
textarea {
overflow: auto;
}
[type="checkbox"],
[type="radio"] {
box-sizing: border-box;
/* 1 */
padding: 0;
/* 2 */
}
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
[type="search"] {
-webkit-appearance: textfield;
/* 1 */
outline-offset: -2px;
/* 2 */
}
[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-file-upload-button {
-webkit-appearance: button;
/* 1 */
font: inherit;
/* 2 */
}
details,
/* 1 */
menu {
display: block;
}
summary {
display: list-item;
}
canvas {
display: inline-block;
}
template {
display: none;
}
[hidden] {
display: none;
}
/* reset */
html,
body,
h1,
h2,
h3,
h4,
h5,
h6,
div,
dl,
dt,
dd,
ul,
ol,
li,
p,
blockquote,
pre,
hr,
figure,
table,
caption,
th,
td,
form,
fieldset,
legend,
input,
button,
textarea,
menu {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
/* 禁止選中文本 */
-webkit-user-select: none;
user-select: none;
font: Oswald, 'Open Sans', Helvetica, Arial, sans-serif
}
/* 禁止長按鏈接與圖片彈出菜單 */
a,
img {
-webkit-touch-callout: none;
}
/*ios android去除自帶陰影的樣式*/
a,
input {
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
input[type="text"] {
-webkit-appearance: none;
}
/* normalize.css */
html {
line-height: 1.15;
/* 1 */
-ms-text-size-adjust: 100%;
/* 2 */
-webkit-text-size-adjust: 100%;
/* 2 */
}
body {
margin: 0;
}
article,
aside,
footer,
header,
nav,
section {
display: block;
}
h1 {
font-size: 2em;
margin: 0.67em 0;
}
figcaption,
figure,
main {
/* 1 */
display: block;
}
figure {
margin: 1em 40px;
}
hr {
box-sizing: content-box;
/* 1 */
height: 0;
/* 1 */
overflow: visible;
/* 2 */
}
pre {
font-family: monospace, monospace;
/* 1 */
font-size: 1em;
/* 2 */
}
a {
background-color: transparent;
/* 1 */
-webkit-text-decoration-skip: objects;
/* 2 */
}
abbr[title] {
border-bottom: none;
/* 1 */
text-decoration: underline;
/* 2 */
text-decoration: underline dotted;
/* 2 */
}
b,
strong {
font-weight: inherit;
}
b,
strong {
font-weight: bolder;
}
code,
kbd,
samp {
font-family: monospace, monospace;
/* 1 */
font-size: 1em;
/* 2 */
}
dfn {
font-style: italic;
}
mark {
background-color: #ff0;
color: #000;
}
small {
font-size: 80%;
}
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
audio,
video {
display: inline-block;
}
audio:not([controls]) {
display: none;
height: 0;
}
img {
border-style: none;
}
svg:not(:root) {
overflow: hidden;
}
button,
input,
optgroup,
select,
textarea {
font-family: sans-serif;
/* 1 */
font-size: 100%;
/* 1 */
line-height: 1.15;
/* 1 */
margin: 0;
/* 2 */
}
button,
input {
/* 1 */
overflow: visible;
}
button,
select {
/* 1 */
text-transform: none;
}
button,
html [type="button"],
/* 1 */
[type="reset"],
[type="submit"] {
-webkit-appearance: button;
/* 2 */
}
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0;
}
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: 1px dotted ButtonText;
}
fieldset {
padding: 0.35em 0.75em 0.625em;
}
legend {
box-sizing: border-box;
/* 1 */
color: inherit;
/* 2 */
display: table;
/* 1 */
max-width: 100%;
/* 1 */
padding: 0;
/* 3 */
white-space: normal;
/* 1 */
}
progress {
display: inline-block;
/* 1 */
vertical-align: baseline;
/* 2 */
}
textarea {
overflow: auto;
}
[type="checkbox"],
[type="radio"] {
box-sizing: border-box;
/* 1 */
padding: 0;
/* 2 */
}
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
[type="search"] {
-webkit-appearance: textfield;
/* 1 */
outline-offset: -2px;
/* 2 */
}
[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-file-upload-button {
-webkit-appearance: button;
/* 1 */
font: inherit;
/* 2 */
}
details,
/* 1 */
menu {
display: block;
}
summary {
display: list-item;
}
canvas {
display: inline-block;
}
template {
display: none;
}
[hidden] {
display: none;
}
/* reset */
html,
body,
h1,
h2,
h3,
h4,
h5,
h6,
div,
dl,
dt,
dd,
ul,
ol,
li,
p,
blockquote,
pre,
hr,
figure,
table,
caption,
th,
td,
form,
fieldset,
legend,
input,
button,
textarea,
menu {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
/* 禁止選中文本 */
-webkit-user-select: none;
user-select: none;
font: Oswald, 'Open Sans', Helvetica, Arial, sans-serif
}
/* 禁止長按鏈接與圖片彈出菜單 */
a,
img {
-webkit-touch-callout: none;
}
/*ios android去除自帶陰影的樣式*/
a,
input {
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
input[type="text"] {
-webkit-appearance: none;
}
*請認真填寫需求信息,我們會在24小時內與您取得聯系。