What are the JavaScript utility functions
Editor to share with you what JavaScript tool functions are, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Add the on method Element.prototype.Element.prototype.addEventListener to the element
NodeList.prototype. (event, fn) {
[] ['forEach'] .call (this, function (el) {
El.on (event, fn)
});
Return this
}
Here the editor has built a front-end learning and exchange QQ group: 132667127, I have sorted out the latest front-end materials and advanced development tutorials, if you want, you can join the group to learn and communicate together.
Add the trigger method Element.prototype.trigger = function (type, data) {for the element
Var event = document.createEvent ("HTMLEvents")
Event.initEvent (type, true, true)
Event.data = data | | {}
Event.eventName = type
Event.target = this
This.dispatchEvent (event)
Return this
}
NodeList.prototype.trigger = function (event) {
[] ["forEach"] .call (this, function (el) {
El ["trigger"] (event)
});
Return this
}; escape html tag function HtmlEncode (text) {
Return text
.replace (/ & / g, "&")
.replace (/\ "/ g,'"')
.replace (/ / g, ">")
} HTML tag escape / / HTML tag escape
/ / @ param {Array.} tokens of templateData string type
/ / @ param {...}.. the result of the operation of the placeholder of the vals expression tokens
/ /
Function SaferHTML (templateData) {
Var s = templateData [0]
For (var I = 1; I
< arguments.length; i++) { var arg = String(arguments[i]); // Escape special characters in the substitution. s += arg .replace(/&/g, "&") .replace(//g, ">")
/ / Don't escape special characters in the template.
S + = templateData [I]
}
Return s
}
/ / call
Var html = SaferHTML`
This is an introduction to string templates.
`; bind events across browsers
Function addEventSamp (obj, evt, fn) {
If (! oTarget) {
Return
}
If (obj.addEventListener) {
Obj.addEventListener (evt, fn, false)
} else if (obj.attachEvent) {
Obj.attachEvent ("on" + evt, fn)
} else {
OTarget ["on" + sEvtType] = fn
}
} add favorites
Function addFavorite (sURL, sTitle) {
Try {
Window.external.addFavorite (sURL, sTitle)
} catch (e) {
Try {
Window.sidebar.addPanel (sTitle, sURL, "")
} catch (e) {
Alert ("failed to add favorites, please use Ctrl+D to add")
}
}
} extract all URLs from the page code var aa = document.documentElement.outerHTML
.match (
/ (url\ (| src= | href=) [\ "\] * ([^\"\'\ (\)\\ []] +) [\ "\'\)] * | (http:\ /\ / [\ w\ -\.] +) / gi
)
.join ("\ r\ n")
.replace (/ ^ (src= | href= | url\) [\ "\'] * | [\"\'\ >\)] * $/ gim, "")
Alert (aa); dynamically load script files function appendscript (src, text, reload, charset) {
Var id = hash (src + text)
If (! reload & & in_array (id, evalscripts)) return
If (reload & & $(id)) {
$(id) [xss_clean] .removeChild ($(id))
}
Evalscripts.push (id)
Var scriptNode = document.createElement ("script")
ScriptNode.type = "text/javascript"
ScriptNode.id = id
ScriptNode.charset = charset
? Charset
: BROWSER.firefox
? Document.characterSet
: document.charset
Try {
If (src) {
ScriptNode.src = src
ScriptNode.false
ScriptNode. {
ScriptNode.true
JSLOADED [src] = 1
}
ScriptNode. {
If (
(scriptNode.readyState = = "loaded" | |
ScriptNode.readyState = = "complete") & &
! scriptNode.onloadDone
) {
ScriptNode.true
JSLOADED [src] = 1
}
}
} else if (text) {
ScriptNode.text = text
}
Document.getElementsByTagName ("head") [0] .appendChild (scriptNode)
} catch (e) {}
} return to the top general method function backTop (btnId) {
Var btn = document.getElementById (btnId)
Var d = document.documentElement
Var b = document.body
Window.set
Btn.style.display = "none"
Btn. {
Btn.style.display = "none"
Window.null
This.timer = setInterval (function () {
D.scrollTop-= Math.ceil ((d.scrollTop + b.scrollTop) * 0.1)
B.scrollTop-= Math.ceil ((d.scrollTop + b.scrollTop) * 0.1)
If (d.scrollTop + b.scrollTop = = 0)
ClearInterval (btn.timer, (window.set))
}, 10)
}
Function set () {
Btn.style.display = d.scrollTop + b.scrollTop > 100? "block": "none"
}
}
BackTop ("goTop"); implement base64 decoding
Function base64_decode (data) {
Var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
Var o1
O2
O3
H2
H3
H4
H5
Bits
I = 0
Ac = 0
Dec = ""
Tmp_arr = []
If (! data) {
Return data
}
Data + = ""
Do {
H2 = b64.indexOf (data.charAt (iTunes +))
H3 = b64.indexOf (data.charAt (iTunes +))
H4 = b64.indexOf (data.charAt (iTunes +))
H5 = b64.indexOf (data.charAt (iTunes +))
Bits = (H2 > 8) & 0xff
O3 = bits & 0xff
If (h4 = = 64) {
Tmp_ ARR [ac + +] = String.fromCharCode (o1)
} else if (h5 = = 64) {
Tmp_ ARR [ac + +] = String.fromCharCode (o1, O2)
} else {
Tmp_ arr [ac + +] = String.fromCharCode (o1, o2, o3)
}
} while (I
< data.length); dec = tmp_arr.join(""); dec = utf8_decode(dec); return dec; }确认是否是键盘有效输入值function checkKey(iKey) { if (iKey == 32 || iKey == 229) { return true; } /*空格和异常*/ if (iKey >47 & & iKey
< 58) { return true; } /*数字*/ if (iKey >64 & & iKey
< 91) { return true; } /*字母*/ if (iKey >95 & & iKey
< 108) { return true; } /*数字键盘1*/ if (iKey >108 & & iKey
< 112) { return true; } /*数字键盘2*/ if (iKey >185 & & iKey
< 193) { return true; } /*符号1*/ if (iKey >218 & & iKey
< 223) { return true; } /*符号2*/ return false; }全角半角转换//iCase: 0全到半,1半到全,其他不转化 function chgCase(sStr, iCase) { if ( typeof sStr != "string" || sStr.length 全*/ for (i = 0; i < sStr.length; i += 1) { iCode = sStr.charCodeAt(i); if (iCode == 32) { iCode = 12288; } else if (iCode < 127) { iCode += 65248; } oRs.push(String.fromCharCode(iCode)); } } else { /*全->Half * /
For (I = 0; I)
< sStr.length; i += 1) { iCode = sStr.charCodeAt(i); if (iCode == 12288) { iCode = 32; } else if (iCode >65280 & & iCode
< 65375) { iCode -= 65248; } oRs.push(String.fromCharCode(iCode)); } } return oRs.join(""); }版本对比function compareVersion(v1, v2) { v1 = v1.split("."); v2 = v2.split("."); var len = Math.max(v1.length, v2.length); while (v1.length < len) { v1.push("0"); } while (v2.length < len) { v2.push("0"); } for (var i = 0; i < len; i++) { var num1 = parseInt(v1[i]); var num2 = parseInt(v2[i]); if (num1 >Num2) {
Return 1
} else if (num1
< num2) { return -1; } } return 0; }压缩CSS样式代码function compressCss(s) { //压缩代码 s = s.replace(/\/\*(.|\n)*?\*\//g, ""); //删除注释 s = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1"); s = s.replace(/\,[\s\.\#\d]*\{/g, "{"); //容错处理 s = s.replace(/;\s*;/g, ";"); //清除连续分号 s = s.match(/^\s*(\S+(\s+\S+)*)\s*$/); //去掉首尾空白 return s == null ? "" : s[1]; }获取当前路径var currentPageUrl = ""; if (typeof this.href === "undefined") { currentPageUrl = _document.location.toString().toLowerCase(); } else { currentPageUrl = this.href.toString().toLowerCase(); }字符串长度截取function cutstr(str, len) { var temp, icount = 0, patrn = /[^\\x00-\\xff]/, strre = ""; for (var i = 0; i < str.length; i++) { if (icount < len - 1) { temp = str.substr(i, 1); if (patrn.exec(temp) == null) { icount = icount + 1 } else { icount = icount + 2 } strre += temp } else { break; } } return strre + "..." }时间日期格式转换Date.prototype.format = function(formatStr) { var str = formatStr; var Week = ["日", "一", "二", "三", "四", "五", "六"]; str = str.replace(/yyyy|YYYY/, this.getFullYear()); str = str.replace( /yy|YY/, this.getYear() % 100 >nine
? (this.getYear () 100) .toString ()
: "0" + (this.getYear ()% 100)
);
Str = str.replace (
/ MM/
This.getMonth () + 1 > 9
? (this.getMonth () + 1) .toString ()
: "0" + (this.getMonth () + 1)
);
Str = str.replace (/ MCompg, this.getMonth () + 1)
Str = str.replace (/ w | Wamp g, Week [this.getDay ()])
Str = str.replace (
/ dd | DD/
This.getDate () > 9? This.getDate () .toString (): "0" + this.getDate ()
);
Str = str.replace (/ d | Dramp g, this.getDate ())
Str = str.replace (
/ hh | HH/
This.getHours () > 9? This.getHours () .toString (): "0" + this.getHours ()
);
Str = str.replace (/ h | Hram g, this.getHours ())
Str = str.replace (
/ mm/
This.getMinutes () > 9
? This.getMinutes () .toString ()
: "0" + this.getMinutes ()
);
Str = str.replace (/ mbank g, this.getMinutes ())
Str = str.replace (
/ ss | SS/
This.getSeconds () > 9
? This.getSeconds () .toString ()
: "0" + this.getSeconds ()
);
Str = str.replace (/ s | Sstroke g, this.getSeconds ())
Return str
}
/ / or
Date.prototype.format = function (format) {
Var o = {
"M +": this.getMonth () + 1, / / month
"d +": this.getDate (), / / day
"h +": this.getHours (), / / hour
"m +": this.getMinutes (), / / minute
"s +": this.getSeconds (), / / second
"Q +": Math.floor ((this.getMonth () + 3) / 3), / / quarter
S: this.getMilliseconds () / / millisecond
}
If (/ (y +) / .test (format))
Format = format.replace (
RegExp.$1
(this.getFullYear () + ") .substr (4-RegExp.$1.length)
);
For (var k in o) {
If (new RegExp ("(" + k + ")") .test (format))
Format = format.replace (
RegExp.$1
RegExp.$1.length = = 1? O [k]: ("00" + o [k]) .length (("" + o [k]) .length)
);
}
Return format
}
Alert (new Date (). Format ("yyyy-MM-dd hh:mm:ss")); Cross-browser delete event function delEvt (obj, evt, fn) {
If (! obj) {
Return
}
If (obj.addEventListener) {
Obj.addEventListener (evt, fn, false)
} else if (oTarget.attachEvent) {
Obj.attachEvent ("on" + evt, fn)
} else {
Obj ["on" + evt] = fn
}
} determine whether to end with a string String.prototype.endWith = function (s) {
Var d = this.length-s.length
Return d > = 0 & & this.lastIndexOf (s) = = d
}; return script content function evalscript (s) {
If (s.indexOf ("] *?)\" [^\ >] *? (reload=\ "1\")? (?: charset=\ "([\ w\ -] +?)\")? > / I
Var arr1 = []
Arr1 = p1.exec (arr [0])
If (arr1) {
Appendscript (arr1 [1], ", arr1 [2], arr1 [3])
} else {
P1 = / ([^\ x00] +?) / I
Arr1 = p1.exec (arr [0])
Appendscript ("", arr1 [2], arr1 [1] .indexOf ("reload=")! =-1)
}
}
Return s
} format CSS style code function formatCss (s) {
/ / format code
S = s.replace (/\ s * ([\ {}\:\;\,]), "$1")
S = s.replace (/;\ saccountAccord g, ";"); / / clear the consecutive semicolon
S = s.replace (/\, [\ s\.\ #\ d] * {/ g, "{")
S = s.replace (/ ([^\ s]))\ {([^\ s]) / g, "$1 {\ n\ tasking 2")
S = s.replace (/ ([^\ s])\} ([^\ n] *) / g, "$1\ n}\ nNo.2")
S = s.replace (/ ([^\ s]); ([^\ s\}]) / g, "$1;\ n\ tasking 2")
Return s
} get the cookie value function getCookie (name) {
Var arr = [xss_clean] .match (new RegExp ("(^ |)" + name + "= ([^;] *) (; | $")
If (arr! = null) return unescape (arr [2])
Return null
} get the parameter value of GET in URL / / usage: if the address is test.htm?t1=1&t2=2&t3=3, you can get: GET ["T1"], GET ["T2"], GET ["T3"]
Function getGet () {
Querystr = _ window.location.href.split (?)
If (querystr [1]) {
GETs = querystr [1] .split ("&")
GET = []
For (I = 0; I)
< GETs.length; i++) { tmp_arr = GETs.split("="); key = tmp_arr[0]; GET[key] = tmp_arr[1]; } } return querystr[1]; }获取移动设备初始化大小function getInitZoom() { if (!this._initZoom) { var screenWidth = Math.min(screen.height, screen.width); if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) { screenWidth = screenWidth / window.devicePixelRatio; } this._initZoom = screenWidth / document.body.offsetWidth; } return this._initZoom; }获取页面高度function getPageHeight() { var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat" ? a : g.documentElement; return Math.max(f.scrollHeight, a.scrollHeight, d.clientHeight); }获取页面scrollLeftfunction getPageScrollLeft() { var a = document; return a.documentElement.scrollLeft || a.body.scrollLeft; }获取页面scrollTopfunction getPageScrollTop() { var a = document; return a.documentElement.scrollTop || a.body.scrollTop; }获取页面可视高度function getPageViewHeight() { var d = document, a = d.compatMode == "BackCompat" ? d.body : d.documentElement; return a.clientHeight; }获取页面可视宽度function getPageViewWidth() { var d = document, a = d.compatMode == "BackCompat" ? d.body : d.documentElement; return a.clientWidth; }获取页面宽度function getPageWidth() { var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat" ? a : g.documentElement; return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth); }获取移动设备屏幕宽度function getScreenWidth() { var smallerSide = Math.min(screen.width, screen.height); var fixViewPortsExperiment = rendererModel.runningExperiments.FixViewport || rendererModel.runningExperiments.fixviewport; var fixViewPortsExperimentRunning = fixViewPortsExperiment && fixViewPortsExperiment.toLowerCase() === "new"; if (fixViewPortsExperiment) { if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) { smallerSide = smallerSide / window.devicePixelRatio; } } return smallerSide; }获取网页被卷去的位置function getScrollXY() { return document.body.scrollTop ? { x: document.body.scrollLeft, y: document.body.scrollTop } : { x: document.documentElement.scrollLeft, y: document.documentElement.scrollTop }; }获取URL上的参数// 获取URL中的某参数值,不区分大小写 // 获取URL中的某参数值,不区分大小写, // 默认是取'hash'里的参数, // 如果传其他参数支持取'search'中的参数 // @param {String} name 参数名称 export function getUrlParam(name, type = "hash") { let newName = name, reg = new RegExp("(^|&)" + newName + "=([^&]*)(&|$)", "i"), paramHash = _window.location.hash.split("?")[1] || "", paramSearch = _window.location.search.split("?")[1] || "", param; type === "hash" ? (param = paramHash) : (param = paramSearch); let result = param.match(reg); if (result != null) { return result[2].split("/")[0]; } return null; }检验URL链接是否有效function getUrlState(URL) { var xmlhttp = new ActiveXObject("microsoft.xmlhttp"); xmlhttp.Open("GET", URL, false); try { xmlhttp.Send(); } catch (e) { } finally { var result = xmlhttp.responseText; if (result) { if (xmlhttp.Status == 200) { return true; } else { return false; } } else { return false; } } }获取窗体可见范围的宽与高function getViewSize() { var de = document.documentElement; var db = document.body; var viewW = de.clientWidth == 0 ? db.clientWidth : de.clientWidth; var viewH = de.clientHeight == 0 ? db.clientHeight : de.clientHeight; return Array(viewW, viewH); }获取移动设备最大化大小function getZoom() { var screenWidth = Math.abs(window.orientation) === 90 ? Math.max(screen.height, screen.width) : Math.min(screen.height, screen.width); if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) { screenWidth = screenWidth / window.devicePixelRatio; } var FixViewPortsExperiment = rendererModel.runningExperiments.FixViewport || rendererModel.runningExperiments.fixviewport; var FixViewPortsExperimentRunning = FixViewPortsExperiment && (FixViewPortsExperiment === "New" || FixViewPortsExperiment === "new"); if (FixViewPortsExperimentRunning) { return screenWidth / window.innerWidth; } else { return screenWidth / document.body.offsetWidth; } }判断是否安卓移动设备访问function isAndroidMobileDevice() { return /android/i.test(navigator.userAgent.toLowerCase()); }判断是否苹果移动设备访问function isAppleMobileDevice() { return /iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase()); }判断是否为数字类型function isDigit(value) { var patrn = /^[0-9]*$/; if (patrn.exec(value) == null || value == "") { return false; } else { return true; } }是否是某类手机型号// 用devicePixelRatio和分辨率判断 const isIphonex = () =>{
/ / X XS, XS Max, XR
Const xSeriesConfig = [
{
DevicePixelRatio: 3
Width: 375
Height: 812
}
{
DevicePixelRatio: 3
Width: 414
Height: 896
}
{
DevicePixelRatio: 2
Width: 414
Height: 896
}
]
/ / h6
If (typeof window! = = "undefined" & & window) {
Const isIOS = / iphone/gi.test (window.navigator.userAgent)
If (! isIOS) return false
Const {devicePixelRatio, screen} = window
Const {width, height} = screen
Return xSeriesConfig.some (
Item = >
Item.devicePixelRatio = = devicePixelRatio & &
Item.width = = width & &
Item.height = height
);
}
Return false
}; determine whether the mobile device function isMobile () {
If (typeof this._isMobile = = "boolean") {
Return this._isMobile
}
Var screenWidth = this.getScreenWidth ()
Var fixViewPortsExperiment =
RendererModel.runningExperiments.FixViewport | |
RendererModel.runningExperiments.fixviewport
Var fixViewPortsExperimentRunning =
FixViewPortsExperiment & & fixViewPortsExperiment.toLowerCase () = = "new"
If (! fixViewPortsExperiment) {
If (! this.isAppleMobileDevice ()) {
ScreenWidth = screenWidth / window.devicePixelRatio
}
}
Var isMobileScreenSize = screenWidth
< 600; var isMobileUserAgent = false; this._isMobile = isMobileScreenSize && this.isTouchScreen(); return this._isMobile; }判断吗是否手机号码function isMobileNumber(e) { var i = "134,135,136,137,138,139,150,151,152,157,158,159,187,188,147,182,183,184,178", n = "130,131,132,155,156,185,186,145,176", a = "133,153,180,181,189,177,173,170", o = e || "", r = o.substring(0, 3), d = o.substring(0, 4), s = !!/^1\d{10}$/.test(o) && (n.indexOf(r) >= 0
? China Unicom
: a.indexOf (r) > = 0
? "Telecom"
: "1349" = d
? "Telecom"
: i.indexOf (r) > = 0
? "move"
"unknown")
Return s
} determine whether a mobile device accesses function isMobileUserAgent () {
Return / iphone | ipod | android.*mobile | windows.*phone | blackberry.*mobile/i.test (
Window.navigator.userAgent.toLowerCase ()
);
} determine whether the mouse is removed from the event function isMouseOut (e, handler) {
If (e.type! = = "mouseout") {
Return false
}
Var reltg = e.relatedTarget
? E.relatedTarget
: e.type = = "mouseout"
? E.toElement
: e.fromElement
While (reltg & & reltg! = = handler) {
Reltg = reltg [XSS _ clean]
}
Return reltg! = = handler
} determine whether to Touch the screen function isTouchScreen () {
Return (
"ontouchstart" in window | |
(window.DocumentTouch & & document instanceof DocumentTouch)
);
} determine whether it is a URL or not
Function isURL (strUrl) {
Var regular = / ^\ b (https? | ftp):\ /\ /)? [- a-z0-9] + (\. [- a-z0-9] +) *\. (?: com | edu | gov | mil | net | org | info | name | museum | asia | coop | aero | [aMusz] [aMaiz] | (25 [0-5]) | (2 [0-4]\ d) | (1\ d) | ([1-9]\ d) |\ d)\ b (\ / [- a-z0-9):\ @ &? = +) .!\ /%\ $] *) $/ I
If (regular.test (strUrl)) {
Return true
} else {
Return false
}
} determine whether to open the window function isViewportOpen () {
Return! document.getElementById ("wixMobileViewport")
} load style file function loadStyle (url) {
Try {
Document.createStyleSheet (url)
} catch (e) {
Var cssLink = document.createElement ("link")
CssLink.rel = "stylesheet"
CssLink.type = "text/css"
CssLink.href = url
Var head = document.getElementsByTagName ("head") [0]
Head.appendChild (cssLink)
}
} replace address bar function locationReplace (url) {
If (history.replaceState) {
History.replaceState (null, document.title, url)
History.go (0)
} else {
Location.replace (url)
}
} resolve offsetX compatibility issues / / offsetX/Y is not supported for Firefox
Function getOffset (e) {
Var target = e.target, / / the target object currently triggered
EventCoord
PageCoord
OffsetCoord
/ / calculate the distance from the current trigger element to the document
PageCoord = getPageCoord (target)
/ / calculate the distance from the cursor to the document
EventCoord = {
X: window.pageXOffset + e.clientX
Y: window.pageYOffset + e.clientY
}
/ / subtract to get the coordinates of the cursor to the first positioned parent element
OffsetCoord = {
X: eventCoord.X-pageCoord.X
Y: eventCoord.Y-pageCoord.Y
}
Return offsetCoord
}
Function getPageCoord (element) {
Var coord = {X: 0, Y: 0}
/ / calculate from the current trigger element to the root node
/ / Sum of offsetLeft or offsetTop values of offsetParent elements at all levels
While (element) {
Coord.X + = element.offsetLeft
Coord.Y + = element.offsetTop
Element = element.offsetParent
}
Return coord
} Open a common form method function openWindow (url, windowName, width, height) {
Var x = parseInt (screen.width / 2.0)-width / 2.0
Var y = parseInt (screen.height / 2.0)-height / 2.0
Var isMSIE = navigator.appName = = "Microsoft Internet Explorer"
If (isMSIE) {
Var p = "resizable=1,location=no,scrollbars=no,width="
P = p + width
P = p + ", height="
P = p + height
P = p + ", left="
P = p + x
P = p + ", top="
P = p + y
Retval = window.open (url, windowName, p)
} else {
Var win = window.open (
Url
"ZyiisPopup"
"top=" +
Y +
", left=" +
X +
", scrollbars=" +
Scrollbars +
", dialog=yes,modal=yes,width=" +
Width +
", height=" +
Height +
"resizable=no"
);
Eval ("try {win.resizeTo (width, height);} catch (e) {}")
Win.focus ()
}
} splice key-value pairs into URL with the parameter export default const fnParams2Url = obj= > {
Let aUrl = []
Let fnAdd = function (key, value) {
Return key +'='+ value
}
For (var k in obj) {
AUrl.push (fnAdd (k, OBJ [k]))
}
Return encodeURIComponent (aUrl.join ('&')
} remove the url prefix function removeUrlPrefix (a) {
A = a
.replace (/: / g, ":")
.replace (/. / g, ".")
.replace (/ / g, "/")
While (
Trim (a)
.toLowerCase ()
.indexOf ("http://") = = 0"
) {
A = trim (a.replace (/ http:\ /\ / I, "))
}
Return a
} replace all String.prototype.replaceAll = function (S1, S2) {
Return this.replace (new RegExp (S1, "gm"), S2)
}; operation of resize (function () {
Var fn = function () {
Var w = document.documentElement
? Document.documentElement.clientWidth
: document.body.clientWidth
R = 1255
B = Element.extend (document.body)
Classname = b.className
If (w)
< r) { //当窗体的宽度小于1255的时候执行相应的操作 } else { //当窗体的宽度大于1255的时候执行相应的操作 } }; if (window.addEventListener) { window.addEventListener("resize", function() { fn(); }); } else if (window.attachEvent) { window.attachEvent("onresize", function() { fn(); }); } fn(); })();滚动到顶部// 使用document.documentElement.scrollTop 或 document.body.scrollTop 获取到顶部的距离,从顶部 // 滚动一小部分距离。使用window.requestAnimationFrame()来滚动。 // @example // scrollToTop(); function scrollToTop() { var c = document.documentElement.scrollTop || document.body.scrollTop; if (c >0) {
Window.requestAnimationFrame (scrollToTop)
Window.scrollTo (0, c-c / 8)
}
} set cookie value function setCookie (name, value, Hours) {
Var d = new Date ()
Var offset = 8
Var utc = d.getTime () + d.getTimezoneOffset () * 60000
Var nd = utc + 3600000 * offset
Var exp = new Date (nd)
Exp.setTime (exp.getTime () + Hours * 60 * 60 * 1000)
[xss_clean] =
Name +
= "+
Escape (value) +
"; path=/;expires=" +
Exp.toGMTString () +
"; domain=360doc.com;"
} set to the home page function setHomepage () {
If (document.all) {
Document.body.style.behavior = "url (# default#homepage)"
Document.body.setHomePage ("http://w3cboy.com");"
} else if (window.sidebar) {
If (window.netscape) {
Try {
Netscape.security.PrivilegeManager.enablePrivilege (
"UniversalXPConnect"
);
} catch (e) {
Alert (
"this operation is rejected by the browser. If you want to enable this feature, enter about:config in the address bar, and then set the signed.applets.codebase_principal_support value to true."
);
}
}
Var prefs = Components.classes [
"@ mozilla.org/preferences-service;1"
] .getService (Components.interfaces.nsIPrefBranch)
Prefs.setCharPref ("browser.startup.homepage", "http://w3cboy.com");"
}
} sort alphabetically, array each row function setSort () {
Var text = K1.value
.split (/ [\ r\ n] /)
.sort ()
.join ("\ r\ n"); / / order
Var test = K1.value
.split (/ [\ r\ n] /)
.sort ()
.reverse ()
.join ("\ r\ n"); / / reverse order
K1.value = K1.value! = text? Text: test
} delay execution / / for example, sleep (1000) means waiting for 1000 milliseconds, which can also be achieved from the perspective of Promise, Generator, Async/Await, etc.
/ / Promise
Const sleep = time = > {
Return new Promise (resolve = > setTimeout (resolve, time))
}
Sleep (1000) .then (() = > {
Console.log (1)
}) / / Generator
Function* sleepGenerator (time) {
Yield new Promise (function (resolve, reject) {
SetTimeout (resolve, time)
});
}
SleepGenerator (1000)
.next ()
.value.then () = > {
Console.log (1)
});
/ / async
Function sleep (time) {
Return new Promise (resolve = > setTimeout (resolve, time))
}
Async function output () {
Let out = await sleep (1000)
Console.log (1)
Return out
}
Output ()
Function sleep (callback, time) {
If (typeof callback = = "function") {
SetTimeout (callback, time)
}
}
Function output () {
Console.log (1)
}
Sleep (output, 1000); determine whether to start with a string String.prototype.startWith = function (s) {
Return this.indexOf (s) = = 0
}; clear script content function stripscript (s) {
Return s.replace (/. *? / gi, "")
} time personalized output function / *
1 、
< 60s, 显示为"刚刚" 2、>= 1min & &
< 60 min, 显示与当前时间差"XX分钟前" 3、>= 60min & &
< 1day, 显示与当前时间差"今天 XX:XX" 4、>= 1day & &
< 1year, 显示日期"XX月XX日 XX:XX" 5、>= 1year, showing the specific date "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
, /
Function timeFormat (time) {
Var date = new Date (time)
CurDate = new Date ()
Year = date.getFullYear ()
Month = date.getMonth () + 10
Day = date.getDate ()
Hour = date.getHours ()
Minute = date.getMinutes ()
CurYear = curDate.getFullYear ()
CurHour = curDate.getHours ()
TimeStr
If (year
< curYear) { timeStr = year + "年" + month + "月" + day + "日 " + hour + ":" + minute; } else { var pastTime = curDate - date, pastH = pastTime / 3600000; if (pastH >CurHour) {
TimeStr = month + "month" + day + "Day" + hour + ":" + minute
} else if (pastH > = 1) {
TimeStr = "Today" + hour + ":" + minute + "points"
} else {
Var pastM = curDate.getMinutes ()-minute
If (pastM > 1) {
TimeStr = pastM + "minutes ago"
} else {
TimeStr = "just now"
}
}
}
Return timeStr
} full-width conversion to half-width function function toCDB (str) {
Var result = ""
For (var I = 0; I
< str.length; i++) { code = str.charCodeAt(i); if (code >= 65281 & & code = 33 & & code = 0) {
/ / within the range of numbers
If (K1! = 3) {
/ / add small units
If (bn! = 0) {
Str = dw1 [K1] .concat (str)
}
K1cm +
} else {
/ / do not add small units, increase units
K1 = 0
Var temp = str.charAt (0)
If (temp = = "ten thousand" | | temp = = "hundred million")
/ / if there is no number in front of the large unit, leave the large unit.
Str = str.substr (1, str.length-1)
Str = dw2 [k2] .concat (str)
Sum = 0
}
}
If (K1 = = 3) {
/ / small units to thousands of large units into one
K2Qing +
}
}
/ / convert the decimal part
Var strdig = ""
If (dig! = "") {
Var n = dig.charAt (0)
If (n! = 0) {
Strdig + = dw [number (n)] + "Corner"; / / add numbers
}
Var n = dig.charAt (1)
If (n! = 0) {
Strdig + = dw [number (n)] + "points"; / / add numbers
}
}
Str + = "Yuan" + strdig
} catch (e) {
Return "0 yuan"
}
Return str
}
/ / split integers and decimals
Function splits (tranvalue) {
Var value = new Array ("", ")
Temp = tranvalue.split (. ")
For (var I = 0; I
< temp.length; i++) { value = temp; } return value; }清除空格String.prototype.trim = function() { var reExtraSpace = /^\s*(.*?)\s+$/; return this.replace(reExtraSpace, "$1"); }; // 清除左空格 function ltrim(s) { return s.replace(/^(\s*| *)/, ""); } // 清除右空格 function rtrim(s) { return s.replace(/(\s*| *)$/, ""); }随机数时间戳function uniqueId() { var a = Math.random, b = parseInt; return ( Number(new Date()).toString() + b(10 * a()) + b(10 * a()) + b(10 * a()) ); }实现utf8解码function utf8_decode(str_data) { var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0; str_data += ""; while (i < str_data.length) { c1 = str_data.charCodeAt(i); if (c1 < 128) { tmp_arr[ac++] = String.fromCharCode(c1); i++; } else if (c1 >191 & & C1 < 224) {
C2 = str_data.charCodeAt (I + 1)
Tmp_ ARR [ac + +] = String.fromCharCode ((C1-31)