Home >Web Front-end >JS Tutorial >(Recommend a super good JS function library) S.Sams Lifexperience ScriptClassLib_javascript skills
1/**//*-------------------------------------------------- -------------
2 * S.Sams Lifexperience
3 * CopyRight (C) 2003-2007 S.Sams Lifexperience ScriptClassLib
4 * MSNLive: S.Sams# msn.com
5 * Http://blog.8see.net/
6 * UPdate by : 2007-01-19 Please retain the copyright for reprinting and dissemination
7 *--------- --------------------------------------------------*/
8
9
10/**//* $ Get the specified object
11 @element Object name
12 You can use the object name collection, and the return value is the collection of objects
13 If you use the Prototype class library, please comment out this function
14 All functions of this function are also implemented in Sams_object.Get()
15*/
16function $(element) {
17 if (arguments.length > 1) {
18 for (var i = 0, elements = [], length = arguments.length; i 19 elements.push($(arguments[i]));
20 return elements;
21 }
22 if (typeof element == 'string')
23 element = document.getElementById(element);
24 return element;
25}
26
27/// 浏览器相关操作
28var Sams_browse = {
29 /**//* Detect browsing information*/
30 checkBrowser : function ()
31 {
32 this.ver=navigator.appVersion
33 this.dom=document.getElementById?1:0
34 this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom)?1:0;
35 this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom)?1:0;
36 this.ie4=(document.all && !this.dom)?1:0;
37 this.ns5=(this.dom && parseInt(this.ver) >= 5) ?1:0;
38 this.ns4=(document.layers && !this.dom)?1:0;
39 this.mac=(this.ver.indexOf('Mac') > -1) ?1:0;
40 this.ope=(navigator.userAgent.indexOf('Opera')>-1);
41 this.ie=(this.ie6 || this.ie5 || this.ie4)
42 this.ns=(this.ns4 || this.ns5)
43 this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns5 || this.ns4 || this.mac || this.ope)
44 this.nbw=(!this.bw)
45 return this;
46 },
47
48 /**//* Set as homepage
49 @url The address to be set as homepage
50*/
51 SetDefault: function ()
52 {
53 this.style.behavior='url(#default#homepage)' ;
54 this.setHomePage(this.GetUrl());
55 return false;
56 },
57
58 /**//* Copy the specified URL address
59 @Msg The character set to be written to the clipboard
60*/
61 SetCopy : function (Msg){
62 if(navigator.userAgent.toLowerCase().indexOf('ie') > -1) {
63 clipboardData.setData('Text',Msg);
64 alert ("Website "" Msg ""
Copied to your clipboard
You can use the Ctrl V shortcut key to paste where you need");
65 69 }
70 },
71
72 /**//* Add to favorites
73 @site Site name
74 @url Address
75*/
76 AddBookmark: function (site, url){
77 if(navigator.userAgent.toLowerCase() .indexOf('ie') > -1) {
78 window.external.addFavorite(url,site)
79 } else if (navigator.userAgent.toLowerCase().indexOf('opera') > - 1) {
80 alert ("Please use Ctrl T to add this page to your favorites");
81 } else {
82 alert ("Please use Ctrl D to add this page to your favorites");
83 }
84 },
85
86 /**//* Open the window with the width and height specified by Url*/
87 OpenWindows: function (url,width,height)
88 {
89 window.open(url,'newwin','width=' width ',height=' height);
90 return false;
91 },
92
93 /**//* Disable browser Javascript error prompts */
94 CloseError: function(){
95 window.onerror = function(){return true;};
96 },
97
98 /**//* Get browser URL* /
99 GetUrl : function(){
100 return location.href;
101 },
102
103 /**//* Get URL parameters*/
104 GetUrlParam: function( ){
105 return location.search;
106 },
107
108 /**//* Get page source*/
109 GetFrom : function(){
110 return document.referrer;
111 },
112
113 /**//* Get the specified URL parameter value
114 @name Parameter name
115*/
116 Request : function(name){
117 var GetUrl = this.GetUrl();
118 var Plist = new Array();
119 if(GetUrl.indexOf('?') > 0)
120 {
121 Plist = GetUrl.split('?')[1].split('&');
122 }
123 else if(GetUrl.indexOf('#') > 0)
124 {
125 Plist = GetUrl.split('#')[1].split('&');
126 }
127 if (GetUrl.length > 0)
128 {
129 for(var i=0; i
131 var GetValue = Plist[i].split('=');
132 if (GetValue[0].toUpperCase() == name.toUpperCase())
133 {
134 return GetValue[1];
135 break;
136 }
137 }
138 return;
139 }
140 },
141
142 /**//* Directly write HTML to a new window
143 @title */
146 Popmsg : function PopIt(title,msg)
147 {
148 var popup = window.open('','popDialog','height=500,width=400,scrollbars=yes');
149 popup.document.write('
' title '
152};
153
154
155/// 对象操作
156var Sams_object = {
157
158 /**//* Create a DIV object
159 @ID The object ID to be created
160 @ClassName Create the object’s Class
161 @SetValue Set the object value
162 @ ToDiv Appends the object to the specified Object, if the specified object does not exist, it will be appended after the Body
163 Returns the created object
164*/
165 CreateDiv : function (ID,ClassName,SetValue,ToDiv){
166 var creatediv = document.createElement('div');
167 if(ID != null) creatediv.id = ID;
168 creatediv.style.position = 'absolute';
169 if(ClassName != null) creatediv.className = ClassName;
170 if(this.Get(ToDiv))
171 {
172 this.Get(ToDiv).appendChild(creatediv);
173 }
174 else
175 {
176 document.getElementsByTagName('body')[0].appendChild(creatediv);
177 }
178 this.SetValue(ID,SetValue);
179 return this.Get(ID);
180 },
181
182 /**//* Delete the specified DIV object
183 @objid The object ID to be deleted
184 Return Bool operation result
185*/
186 DeleteDiv : function (objid)
187 {
188 try
189 {
190 if(this.Get(objid))
191 {
192 var GetParent = this.Get(objid).parentNode;
193 GetParent.removeChild(this.Get(objid));
194 return true;
195 }
196 else
197 {
198 return false;
199 }
200 }
201 catch(e)
202 {
203 return false;
204 }
205 },
206
207 /**//* Get the browser object
208 @id The object ID to be obtained
209 You can use the object name collection, and the return value is the collection of objects
210*/
211 Get : function (objid) {
212 if (arguments.length > 1) {
213 for (var i = 0, objids = [], length = arguments.length; i 214 objids.push(this.Get(arguments[i]));
215 return objids;
216 }
217 if (typeof objid == 'string')
218 {
219 if (document.getElementById) {
220 objid = document.getElementById(objid);
221 } else if (document.all) {
222 objid = document.all[objid];
223 } else if (document.layers) {
224 objid = document.layers[objid];
225 }
226 }
227 return objid;
228 },
229
230 /**//* Get the value of the object
231 @objid Object ID
232*/
233 GetValue : function (objid) {
234 if (typeof objid == 'string')
235 {
236 var getTagName = this.Get(objid).tagName.toLowerCase();
237 if (getTagName == 'input' || getTagName == 'textarea' || getTagName == 'select')
238 {
239 return this.Get(objid).value;
240 }
241 else if (getTagName == 'div' || getTagName == 'span')
242 {
243 return this.Get(objid).innerText;
244 }
245 }
246 else if (typeof objid == 'object')
247 {
248 return objid.value;
249 }
250 },
251
252 /**//* Set the value of the specified object to implement direct assignment or clearing operations
253 @objid Object ID
254 @inserValue Pass in the value (optional Null: clear the value of the ID, then assign the value directly)
255*/
256 SetValue: function(objid,inserValue) {
257 var getTagName = this.Get(objid).tagName.toLowerCase();
258 if (inserValue == null) inserValue = '';
259 if (getTagName == 'input' || getTagName == 'textarea')
260 {
261 this.Get(objid).value = inserValue;
262 }
263 else if (getTagName == 'div' || getTagName == 'sapn')
264 {
265
266 this.Get(objid).innerText = inserValue;
267 }
268 },
269
270 /**//* Copy the object value to the clipboard
271 @str Object value
272*/
273 CopyCode : function (str) {
274 var rng = document.body.createTextRange();
275 rng.moveToElementText(str);
276 rng.scrollIntoView();
277 rng.select();
278 rng.execCommand("Copy");
279 rng.collapse(false);
280 },
281
282 /**//* Show and hide an object
283 @Objid Object ID
284 @isshow For specific operations, specify Obj as False: none or True: block (optional)
285*/
286 ShowHidd : function(objid,isshow){
287 if (isshow != null)
288 {
289 if(isshow)
290 {
291 this.Get(objid).style.display = 'block';
292 }
293 else
294 {
295 this.Get(objid).style.display = 'none';
296 }
297 }
298 else
299 {
300 if(this.Get(objid).style.display == 'none')
301 {
302 this.Get(objid).style.display = 'block';
303 }
304 else
305 {
306 this.Get(objid).style.display = 'none';
307 }
308 }
309 },
310
311 /**//* Is the current object visible?
312 @objid Object ID
313*/
314 IsVisible : function(objid){
315 if(this.Get(objid))
316 {
317 try
318 {
319 if (this.Get(objid).style.display == 'none')
320 {
321 return false
322 }
323 if(this.Get(objid).style.visibility == 'hidden')
324 {
325 return false;
326 }
327 return true;
328 }
329 catch(e)
330 {
331 return false;
332 }
333 }
334 else
335 {
336 return false;
337 }
338 }
339};
340
341/// 字符处理
342var Sams_string = {
343 /**//* Get the value of the specified length on the left
344 @str The character set to be processed
345 @n Length
346*/
347 Left : function (str,n)
348 {
349 if(str.length > 0)
350 {
351 if(n>str.length) n = str.length;
352 return str.substr(0,n)
353 }
354 else
355 {
356 return;
357 }
358 },
359
360 /**//* Get the value of the specified length on the right
361 @str The character set to be processed
362 @n Length
363*/
364 Right : function (str,n)
365 {
366 if(str.length > 0)
367 {
368 if(n>=str.length) return str;
369 return str.substr(str.length-n,n);
370 }
371 else
372 {
373 return;
374 }
375 },
376
377 /**//* Trim: Clear spaces on both sides
378 @str Character set to be processed
379*/
380 Trim : function (str)
381 {
382 if (typeof str == 'string') return str.replace(/(^s*)|(s*$)/g, '');
383 },
384
385 /**//* LTrim: Clear the spaces on the left
386 @str The character set to be processed
387*/
388 Ltrim : function (str)
389 {
390 if (typeof str == 'string') return str.replace(/(^s*)/g, '');
391 },
392
393 /**//* RTrim: Clear the space on the right
394 @str The character set to be processed
395*/
396 Rtrim : function (str)
397 {
398 if (typeof str == 'string') return str.replace(/(s*$)/g, '');
399 },
400
401 /**//* Clear non-characters before and after
402 @str Character set to be processed
403*/
404 strip : function(str) {
405 if (typeof str == 'string') return str.replace(/^s /, '').replace(/(^s*)|(s*$)/g, '');
406 },
407
408 /**//* Filter the HTML tags in the characters
409 @str The character set to be processed
410*/
411 stripTags : function(str) {
412 if (typeof str == 'string')return str.replace(/?[^>] >/gi, '').replace(/(^s*)|(s*$)/g, '');
413 }
414};
415
416/// Variable value
417var Sams_time = {
418 /**//* Get today’s date yyyy-MM-dd*/
419 GetDateNow : function (){
420 var d, y,m,dd;
421 d = new Date();
422 y = d.getYear();
423 m = d.getMonth() 1;
424 dd = d.getDate();
425 return y "-" m "-" dd;
426 },
427
428 /**//* Get the date value of a specific number of days after the specified date
429 @toDate The currently specified date
430 @N The number of dates to add
431*/
432 AddDays : function(toDate,N){
433 var aDate=this._cvtISOToDate(toDate);
434 if ( ! aDate ) return " " ;
435 var millis=86400000 *N;
436 aDate=new Date(aDate.getTime() millis);
437 return this . _ fmtDate ISO ( aDate ) ;
438 },
439 _fmtDateISO : function ( aDate ) {
440 with ( aDate ) {
441 var mm=getMonth() 1 ;
442 if (mm443 var dd=getDate();
444 if (dd445 return (getFullYear() '-'mm'-'dd);
446 }
447 },
448 _cvtISOToDate : function (isoDate) {
449 var atomDate= isoDate.split('-');
450 var aDate=new Date(parseInt(atomDate[0],10),parseInt(atomDate[1],10)-1,parseInt(atomDate[2],10),6,0,0);
451 } 453 } 451 return aDate ;
452}
453};
454
455/// Unit value
456var Sams_media = {
457 /**//* Add the middle mouse button zoom function to a single image. For batches, you can directly use ResizeImage (specify the image size to add this function: Int) (this function is only applicable to IE)
458 objid Object ID
459*/
460 ZoomFun : function(objid){
461 Sams_object. Get ( objid ) . onmousewheel = function ( ) { return Sams_media . imagecontrol ( this );}
462 },
463
464 /**//* Reset the image size and add the zoom function (this function is only applicable to IE)
465 @IntSize Specify the size of the image
466 If it fits the image size, add the zoom function
467*/
468 ResizeImage: function (IntSize) {
469 var imgsinlog=document.getElementsByTagName('img');
470 for( j=0; j471 if (imgsinlog[j].width >= IntSize) {
472 imgsinlog[j].width = IntSize; imgsinlog[j ].style.cursor= 'pointer';
474 imgsinlog[j].onclick = function() {window.open(this.src);}
475 if (navigator.userAgent.toLowerCase().indexOf ('ie') > -1) {
476 imgsinlog[j].title = 'You can use the middle mouse button or the Ctrl mouse wheel to zoom in and out of the picture, click the picture to open it in a new window'; [j].onmousewheel = function(){return Sams_media.imagecontrol(this);};
478 Open in new window';
482 var zoom=parseInt(obj.style .zoom, 10)||100; zoom =event.wheelDelta/12;
488 if (zoom>0) obj.style.zoom=zoom '%';
489 return false;
490 } ,
491
492 /**//* If there is an exception such as the image cannot be downloaded, the error message displayed
493 @errimgpath The image path of the error message displayed
494*/
495 ImagesError: function(errimgpath){
496 var imglist = document.getElementsByTagName('img');
497 for( j=0; j498 imglist[j].onerror = function(){
499 this.src = errimgpath;
500 }
501 }
502 },
503
504 /**//* Display media
505 @mFile File path
506 @mFileType File type (can be empty, if it is Flash, specify swf type)
507 @ObjID Object ID
508 @mWidth Displayed object width
509 @mHeight Displayed object height
510 Note: You can specify the ID of the object. If the ID does not exist, it will be automatically created and appended after the Body
511*/
512 ShowMedia : function (mFile, mFileType, ObjID, mWidth, mHeight) {
513 var mediaStr;
514 switch(mFileType){
515 case "swf":
516 mediaStr="";
517 break;
518 default :
519 mediaStr="";
520 }
521
522 var mediaDiv = Sams_object.Get(ObjID);
523
524 if (mediaDiv) {
525 mediaDiv.innerHTML = mediaStr;
526 }
527 else
528 {
529 mediaDiv = document.createElement("div");
530 mediaDiv.id = ObjID;
531 mediaDiv.innerHTML = mediaStr;
532 document.getElementsByTagName('body')[0].appendChild(mediaDiv);
533 }
534 return false;
535 }
536};
537
538/// 样式相关操作
539var Sams_style = {
540 /**//* Change the font size
541 @objid Object ID
542 @size Font size
543*/
544 doZoom : function (objid,size){
545 Sams_object.Get(objid).style.fontSize=size 'px';
546 },
547
548 /**//* Change the style of the specified object
549 @objid Object ID
550 @className The ClassName to be changed
551*/
552 ClassName: function(objid, className) {
553 Sams_object.Get(objid).className = className;
554 },
555
556 /**//* Object positioning
557 @obj The object to be positioned
558 Returns the array object of the X.Y result
559*/
560 GotoXY : function (obj) {
561 var t=obj.offsetTop;
562 var l=obj.offsetLeft;
563 while(obj=obj.offsetParent){
564 t =obj.offsetTop;
565 l =obj.offsetLeft;
566 }
567 return Array(t,l);
568 }
569};
570
571/// 科学计算
572var Sams_account = {
573 /**//* Count every 1 to 10
574 @ Value
575*/
576 GetTen: function (i)
577 {
578 var items_One,Get_One;
579 if (i.length > 1&& (/^d $/.test(i)))
580 {
581 items_One = i.substr(0,i.length-1);
582 Get_One = i.substr(i.length-1,1);
583 if (parseInt(Get_One)>0)
584 {
585 items_One = parseInt(items_One) 1;
586 items_One = items_One '0';
587 }
588 else
589 {
590 items_One = items_One '0';
591 }
592 }
593 else
594 {
595 items_One = i;
596 }
597 return items_One;
598 }
599};
600
601/// 数据验证(所有数值返回值均为Bool型)
602var Sams_validate = {
603 /**//* Whether it is numeric data
604 @str Character set
605*/
606 IsNumber : function(str){
607 if (/^d $/.test(str)){return true;}else{return false;}
608 },
609
610 /**//* Whether it is numeric data
611 @objid Object ID
612*/
613 IsNumberObj : function(objid){
614 return this.IsNumber(Sams_object.GetValue(objid));
615 },
616
617 /**//* Whether it is natural number data
618 @str Character set
619*/
620 IsInt : function(str){
621 if (/^( |-)?d $/.test(str)){return true;}else{return false;}
622 },
623
624 /**//* Whether it is natural number data
625 @objid Object ID
626*/
627 IsIntObj : function(objid){
628 return this.IsInt(Sams_object.GetValue(objid));
629 },
630
631 /**//* Is it a Chinese character
632 @str Character set
633*/
634 IsChinese : function(str)
635 {
636 if (/^[u4e00-u9fa5] $/.test(str)){return true;}else{return false;}
637 },
638
639 /**//* Is it a Chinese character
640 @objid Object ID
641*/
642 IsChineseObj : function(objid)
643 {
644 return this.IsChinese(Sams_object.GetValue(objid));
645 },
646
647 /**//* Is it an English letter
648 @str Character set
649*/
650 IsLower : function(str)
651 {
652 if (/^[A-Za-z] $/.test(str)){return true}else{return false;}
653 },
654
655 /**//* Is it an English letter
656 @objid Object ID
657*/
658 IsLowerObj : function(objid)
659 {
660 return this.IsLower(Sams_object.GetValue(objid));
661 },
662
663 /**//* Is it the correct URL?
664 @str Character set
665*/
666 IsUrl : function(str)
667 {
668 var myReg = /^((http:[/][/])?w ([.]w |[/]w*)*)?$/;
669 if(myReg.test(str)){return true;}else{return false;}
670 },
671
672 /**//* Is it the correct URL
673 @objid Object ID
674*/
675 IsUrlObj : function(objid)
676 {
677 return this.IsUrl(Sams_object.GetValue(objid));
678 },
679
680 /**//* Is it the correct email format?
681 @str Character set
682*/
683 IsEmail : function(str)
684 {
685 var myReg = /^([-_A-Za-z0-9.] )@([_A-Za-z0-9] .) [A-Za-z0-9]{2,3}$/;
686 if(myReg.test(str)){return true;}else{return false;}
687 },
688
689
690 /**//* Is it the correct email format?
691 @objid Object ID
692*/
693 IsEmailObj : function(objid)
694 {
695 return this.IsEmail(Sams_object.GetValue(objid));
696 },
697
698 /**//* Is it the correct mobile phone number
699 @str Character set
700*/
701 IsMobile : function(str)
702 {
703 var regu =/(^[1][3][0-9]{9}$)|(^0[1][3][0-9]{9}$)/;
704 var re = new RegExp(regu);
705 if (re.test(str)){return true;}else{return false;}
706 },
707
708 /**//* Is it the correct mobile phone number
709 @objid Object ID
710*/
711 IsMobileObj : function(objid)
712 {
713 return this.IsMobile(Sams_object.GetValue(objid));
714 }
715};
716
717/**//*
718 Implementing Ajax function
719 Sams_ajax.SendRequest('GET', url, null, recall, "addtohome");
720 Sams_ajax.SendRequest('GET', url, null, null );
721 obj.responseText;
722*/
723var Sams_ajax = {
724 _objPool: [],
725 _getInstance: function (){
726 for (var i = 0; i 727 if (this._objPool[i].readyState == 0 || this._objPool[i].readyState == 4){
728 return this._objPool[i];
729 }
730 }
731 this._objPool[this._objPool.length] = this._createObj();
732 return this._objPool[this._objPool.length - 1];
733 },
734 _createObj : function (){
735 if (window.XMLHttpRequest){
736 var objXMLHttp = new XMLHttpRequest();
737 }
738 else{
739 var MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
740 for(var n = 0; n 741 try{
742 var objXMLHttp = new ActiveXObject(MSXML[n]);
743 break;
744 }
745 catch(e){
746 }
747 }
748 }
749 if (objXMLHttp.readyState == null){
750 objXMLHttp.readyState = 0;
751 objXMLHttp.addEventListener("load", function (){
752 objXMLHttp.readyState = 4;
753 if (typeof objXMLHttp.onreadystatechange == "function"){
754 objXMLHttp.onreadystatechange();
755 }
756 }, false);
757 }
758 return objXMLHttp;
759 },
760
761 /// 开始发送请求
762 SendRequest : function (method, url, data, callback,funparam,funparam2){
763 var objXMLHttp = this._getInstance();
764 with(objXMLHttp){
765 try{
766 if (url.indexOf("?") > 0){
767 url = "&randnum=" Math.random();
768 }
769 el