1, the name of pure English numbers and other non-newline problems

span {
    word-wrap: break-word;
    word-break: break-all;
} Copy the code

2, each browser on the adaptation of gradient

.main {
  background: linear-gradient(left, #055798, #01b1f8);
  background: -webkit-linear-gradient(left, #055798, #01b1f8);
  background: -ms-linear-gradient(left, #055798, #01b1f8);
  background: -moz--linear-gradient(left, #055798, #01b1f8);
  background: -0--linear-gradient(left, #055798, #01b1f8);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='# 055798', endColorstr='#01b1f8',GradientType=1 ); / / the default, level / * filter: progid: DXImageTransform. Microsoft. Gradient (startColorstr ='# 055798', endColorstr='#01b1f8',GradientType=0 ); // vertical */}Copy the code

3, too much content need a line display, display incomplete ellipsis

span { display: block; height: 17px; overflow: hidden; white-space: nowrap; // A line showing text-overflow: ellipsis; // omit}Copy the code

4, mouse wheel event, the adaptation of each browser

Link address: www.cnblogs.com/walkingp/ar…

/*IE/Opera register event */if(document.attachEvent){
     document.attachEvent('onmousewheel',scrollFunc); } /*Firefox registration event */if(document.addEventListener){
    document.addEventListener('DOMMouseScroll',scrollFunc,false); } /*Safari is of the same type as Chrome, you can use HTML DOM to add events */ window.onmousewheel=document.onmousewheel=scrollFunc; //IE/Opera/Chrome /* You can add events using HTML DOM, so add events using the following methods */ /* Register events */if(document.addEventListener){
    document.addEventListener('DOMMouseScroll',scrollFunc,false); }//W3C window.onmousewheel=document.onmousewheel=scrollFunc; //IE/Opera/ChromeCopy the code

5. Uploading scroll bar display problem

$.messager.progress({interval:'99999999'}); Var formData = new formData (); var mutiUpload=document.getElementById('updateFile').files;
for(var i=0; i<mutiUpload.length; i++){ formData.append("filelist", mutiUpload[i]);
}
formData.append("zyname", $("#addResource [name='zyname']").val());
formData.append("dagang", $("#addResource [name='dagang']").val());
formData.append("rangetype", $("#addResource [name='rangetype']").val());
formData.append("whether", $("#addResource [name='whether']").val());

$.ajax({
    url: webPath + '/wechat/Resourcesmanage/addListResources.htm'.type: "POST",
    data: formData,
    processData: false// Do not serialize the data argument, default istrue
    contentType: false// Do not set the content-Type request header because the file data is encoded as multipart/form-data XHR:function(){
        myXhr = $.ajaxSettings.xhr();
        if(myXhr.upload){
          myXhr.upload.addEventListener('progress'.function(e) {
            if (e.lengthComputable) {
              var percent = Math.floor(e.loaded/e.total*100);
              if(percent <= 100) {
                $(".progressbar-text").text(percent+The '%');
                $(".progressbar-value").css('width', percent+The '%');
              }
              if(percent > 100) {
              }
            }
          }, false);
        }
        returnmyXhr; }, success:functionParse (obj){var data= json.parse (obj);if(data.status==1){
			$.messager.progress('close');
			layerOpen('tip'.'Added successfully! '); / / $('#win_add_Excel').window('close');
			$('.add-resource-file').fadeOut();
			$('.z_photo').html(' ');
			$('#addResource')[0].reset();
			initResources(pageNo,resSize,"".""."");
		}else{
			$.messager.progress('close');
		     layerOpen('tip',data.msg);
		}
    },
    error: function(res) {// Request failed console.log(res); }});Copy the code

6. IE6-IE8 supports HTML5 tags

<! - [ifLt IE 9]> <script SRC ="/ / cdn.bootcss.com/respond.js/1.4.2/respond.js"> < / script > < script SRC ="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script> <! [endif] -- > //html5shiv: Solve the problem that THE following browsers of IE9 do not recognize the new html5 tags and cause CSS to not work. Respond. min: Let browsers that do not support CSS3 Media Query, including Internet Explorer 6 to Internet Explorer 8, support Query.Copy the code

IE6 has a bug with the default height of block-level elements

#dv_placeholder div {font: 1px/1 serif; /** Clear block default height @ie6 **/}Copy the code

8. Change the scroll bar style

www.poluoluo.com/jzxy/201104/114964.html www.webhek.com/post/scroll…

9. Detailed explanation of false elements

www.cnblogs.com/xiaohuochai…

10. Check the browser model and version

Blog.csdn.net/u011380927/…

/** * If you want to check the current browser model and version, you need to use jquery-migrate-1.2.1.min.js */function judgeBroswer() {
    if ($.browser.msie) {
        alert("this is msie! version:" + $.browser.version);
    } else if ($.browser.safari) {
        alert("this is safari! version:" + $.browser.version);
    } else if ($.browser.mozilla) {
        alert("this is mozilla! version:" + $.browser.version);
    } else if ($.browser.opera) {
        alert("this is opera version:" + $.browser.version);
    } else if ($.browser.chrome) {
        alert("this is chrome version:"+ $.browser.version); }}Copy the code

Js date and time formatting

// Format the date'2016-06-17'.replace(/(\d{4})-(\d{2})-(\d{2})/g,'$1 year $2 month $3 ')
"June 17, 2016"; // Date format /** method 1**/ / the extension to Date, convert Date to the specified format String // month (M), day (d), hour (h), minute (M), second (s), quarter (q) can use 1 or 2 placeholders, // Year (y) can use 1 to 4 placeholders, milliseconds (S) can only use 1 to 3 placeholders // Example: // (new Date()).format ()"yyyy-MM-dd hh:mm:ss.S") = = > 2006-07-02 08:09:04. 423 / / (new Date ()). The Format ("yyyy-M-d h:m:s.S"Format ==> date.prototype.Format =function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //"d+": this getDate (), / / day"h+": this.gethours (), // hours"m+": this getMinutes (), / / min"s+": this getSeconds (), / / SEC"q+"Math.floor((this.getMonth() + 3) / 3), // quarter"S": this.getmilliseconds () // milliseconds};if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.The $1, (this.getFullYear() + "").substr(4 - RegExp.The $1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.The $1, (RegExp.The $1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    returnfmt; } var time1 = new Date().format ()"yyyy-MM-dd");
var time2 = new Date().Format("yyyy-MM-dd hh:mm:ss");Copy the code
/** / <script language="javascript" type="text/javascript"> <! -- /** * extension to Date, Convert Date to String in the specified format * Month (M), day (d), 12 hour (h), 24 hour (h), minute (M), second (s), week (E), quarter (q) can use 1-2 placeholders * year (y) can use 1-4 placeholders. * eg: * (new Date()).pattern()"yyyy-MM-dd hh:mm:ss.S") = = > 2006-07-02 08:09:04. 423 * (new Date ()). The pattern ("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04 * (new Date()).pattern()"yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 tue 08:09:04 * (new Date()).pattern()"yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 tue 08:09:04 * (new Date()).pattern()"yyyy-M-d h:m:s.S"*/ date.prototype.pattern ==function(fmt) {
    var o = {
    "M+": this.getMonth()+1, //"d+": this getDate (), / / day"h+": this.getHours()%12 == 0 ? 12: this.gethours ()%12, // hours"H+": this.gethours (), // hours"m+": this getMinutes (), / / min"s+": this getSeconds (), / / SEC"q+"Math.floor((this.getMonth()+3)/3), // quarter"S": this.getmilliseconds () // milliseconds}; var week = {"0" : "/u65e5"."1" : "/u4e00"."2" : "/u4e8c"."3" : "/u4e09"."4" : "/u56db"."5" : "/u4e94"."6" : "/u516d"
    };
    if(/(y+)/.test(fmt)){
        fmt=fmt.replace(RegExp.The $1, (this.getFullYear()+"").substr(4 - RegExp.The $1.length));
    }
    if(/(E+)/.test(fmt)){
        fmt=fmt.replace(RegExp.The $1, ((RegExp.The $1.length>1) ? (RegExp.The $1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);
    }
    for(var k in o){
        if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.The $1, (RegExp.The $1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); }}return fmt;
}

var date = new Date();
window.alert(date.pattern("yyyy-MM-dd hh:mm:ss")); / / -- > < / script > / * * / * * method 3 Date. The prototype. The format =function (mask) {
    var d = this;

    var zeroize = function (value, length) {

            if(! length) length = 2; value = String(value);for (var i = 0, zeros = ' '; i < (length - value.length); i++) {

                zeros += '0';

            }

            return zeros + value;

        };

    return mask.replace(/"[^"] *"|'[^']*'|/b ( ? : d {
        1, 4
    } | m {
        1, 4
    } | yy( ? : yy) ? | ([hHMstT]) / 1 ? | [lLZ]) / b / g, function ($0) {

        switch ($0) {

        case 'd':
            return d.getDate();

        case 'dd':
            return zeroize(d.getDate());

        case 'ddd':
            return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];

        case 'dddd':
            return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];

        case 'M':
            return d.getMonth() + 1;

        case 'MM':
            return zeroize(d.getMonth() + 1);

        case 'MMM':
            return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];

        case 'MMMM':
            return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];

        case 'yy':
            return String(d.getFullYear()).substr(2);

        case 'yyyy':
            return d.getFullYear();

        case 'h':
            return d.getHours() % 12 || 12;

        case 'hh':
            return zeroize(d.getHours() % 12 || 12);

        case 'H':
            return d.getHours();

        case 'HH':
            return zeroize(d.getHours());

        case 'm':
            return d.getMinutes();

        case 'mm':
            return zeroize(d.getMinutes());

        case 's':
            return d.getSeconds();

        case 'ss':
            return zeroize(d.getSeconds());

        case 'l':
            return zeroize(d.getMilliseconds(), 3);

        case 'L':
            var m = d.getMilliseconds();

            if (m > 99) m = Math.round(m / 10);

            return zeroize(m);

        case 'tt':
            return d.getHours() < 12 ? 'am' : 'pm';

        case 'TT':
            return d.getHours() < 12 ? 'AM' : 'PM';

        case 'Z':
            return d.toUTCString().match(/[A-Z]+$/);

            // Return quoted strings with the surrounding quotes removed

        default:
            return $0.substr(1, $0.length - 2); }}); };Copy the code

12, window. Url. Createobjecturl multiple browser compatibility

(IE, Google, 360, Safari, firefox) blog.csdn.net/ybb35068001…

<script type="text/javascript">   
function setImagePreview() {
    var docObj = document.getElementById("ctl00_ContentMain_file_head");
    var fileName = docObj.value;
    if(! fileName.match(/.jpg|.gif|.png|.bmp/i)) { alert('The picture you uploaded is not formatted correctly, please select it again! ');
        return false;
    }

    var imgObjPreview = document.getElementById("preview");
    if(docObj. Files & & docObj. Files [0]) {/ / firefox, directly set attribute imgObjPreview img. Style.css. Display ='block';
        imgObjPreview.style.width = '63px';
        imgObjPreview.style.height = '63px';
        //imgObjPreview.src = docObj.files[0].getAsDataURL();   
        if (window.navigator.userAgent.indexOf("Chrome") >= 1 || window.navigator.userAgent.indexOf("Safari") >= 1) {
            imgObjPreview.src = window.webkitURL.createObjectURL(docObj.files[0]);
        } else{ imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]); }}else{// in IE, use docobj.select (); docObj.blur(); var imgSrc = document.selection.createRange().text; varlocalImagId = document.getElementById("localImag"); // The initial size must be setlocalImagId.style.width = "63px";
        localImagId.style.height = "63px"; // Prevent users from modifying the suffix to fake the image try {localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
            localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
        } catch(e) {
            alert("The picture you uploaded is not formatted correctly, please select it again!");
            return false;
        }
        imgObjPreview.style.display = 'none';
        document.selection.empty();
    }
    return true;
}  
  
</script>   

<div id="localImag"><img id="preview" width="1" height="1" style="display:none" /></div> 
<asp:FileUpload ID="file_head" runat="server" onchange="javascript:setImagePreview();" /> 


//http://blog.csdn.net/qq_24148225/article/details/53187149?locationNum=5&fps=1
if(navigator.userAgent.indexOf("MSIE 9.0"Var PIC = document.getelementById (); var PIC = document.getelementById ();"showLogo"),  
     file = document.getElementById("logo"); file.select(); / / due to the security of Internet explorer 9, if no focus () on other button, div, etc., the document. The selection, createRange (). The text will be an error / / (here is a save button, To focus on a div, the div must be at least 1px."save").focus();  
      //file.blur();  
      var reallocalpath = document.selection.createRange().text;  
      pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src=\"" + reallocalpath + "\")"; Pic.style.width = // Add a filter"180px";  
      pic.style.height = "130px"; // Set img SRC to base64 encoded transparent image to undisplay browser default image pic.src ='data:image/gif; base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';  
  
}else{// Other browsers document.getelementById ("showLogo").src =getFileUrl("logo");   
  
}  
  
  
function getFileUrl(fileName){  
     var url ;             
     if (navigator.userAgent.indexOf("MSIE")>=1) {  
          url = document.getElementById(sourceId).value; // IE10,11 can use this method}else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox  
          url = window.URL.createObjectURL(document.getElementById(fileName).files.item(0));  
     } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome  
          url = window.URL.createObjectURL(document.getElementById(fileName).files.item(0));  
     } else{  
          url = window.URL.createObjectURL(document.getElementById(fileName).files.item(0));  
     }  
     return url;  
  
}Copy the code

13. Prohibit right-click and copy-paste events

//http://www.cnblogs.com/ZDPPU/p/5950408.html 

Oncontextmenu event single disable right-click menu on a page, BODY with onContextMenu =’return false’ to remove the right mouse button; Set in JS oncontextmenu = ‘return true’ in the window. The document. The oncontextmenu = function () {return false. }

onconTextmenu=window.event.returnValue=false; Right-click menu disable, use this to disable replication.

Add attribute code to <body> :

oncontextmenu="return false"

onselectstart="return false"// Disallow content on the page onCopy ="return false"// Prevent copying the content selected by the user on the web pageCopy the code

Prevent users from saving web pages: use the
tag to prevent web pages from being saved directly, but not from being downloaded by a tool

* is a wildcard character.

Case 1:

< HTML > <head> <title>OnContextMenu event </title> <script language="JavaScript"> <! --function uFunction()

{     document.all.infoDiv.innerHTML='You pressed the right mouse button, but the right mouse button menu doesn't show up! '; }function uFunction2()

{    document.all.infoDiv.innerHTML='You press Ctrl+ right mouse button to display the right mouse button menu. '; } //--> </script> </head> <body oncontextmenu="if(! event.ctrlKey){uFunction(); return false}else{uFunction2()}">

<div id="infoDiv"> You pressed the right mouse button, but the right mouse button menu cannot be displayed! <br> You press Ctrl+ right mouse button to display the right mouse button menu. </div></body> </html>Copy the code

 

// Disable mouse events document.onmouseDown =function(e){
    if(e.white == 2){// The mouse wheel is pressed and scrolling is not triggeredreturn false;
    }
    if(e.white ==3){// right mouse buttonreturn false; }} // Disable CTRL, Alt,shift
document.onkeydown = function() {if( event.ctrlKey ){
        return false;
    }
    if ( event.altKey ){
        return false;
    }
    if ( event.shiftKey ){
        return false;
    }
}

oncontextmenu='return false'
ondragstart='return false'
onselectstart ='return false'
onselect='document.selection.empty()'
oncopy='document.selection.empty()'
onbeforecopy='return false'
onmouseup='document.selection.empty()' Copy the code

An easier way to do this is to add the following code to <body> so that the left and right mouse buttons are disabled.

topmargin="0"
oncontextmenu="return false" 
ondragstart="return false" 
onselectstart="return false" 
onselect="document.selection.empty()"
oncopy="document.selection.empty()" 
onbeforecopy="return false"
onmouseup="document.selection.empty()"/ / 1. Disallow webpage saving as: Add the following code after <body> : <noscript> <iframe SRC ="*.htm"> < iframe > < / noscript > / / 2. Prohibit web content duplication. Paste: Add the following code to <body> : <body onMousemove =/HideMenu()/ onContextMenu ="return false"
ondragstart="return false" onselectstart ="return false"
onselect="document.selection.empty()"
oncopy="document.selection.empty()" onbeforecopy="return false"
onmouseup="document.selection.empty()">Copy the code

An editable div filters out special styles or labels for pastes

<! DOCTYPE html PUBLIC"- / / / / W3C DTD XHTML 1.0 Transitional / / EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title> No title document </title> </head> <body> <div id="test" style="float: left; height: 100px; width: 500px; border:1px solid red" contenteditable="true" class="testmr">2222</div>
  </body>

</html>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){

   var update = function(original){
   var new_content = $('.testmr').html();

   var new_content = new_content.replace(/class="[^"] +"/ig, ''); new_content = new_content.replace(/class\="[^"] +"/gi, ' '); new_content = new_content.replace(/<h1.*? > (. *?) <\/h1>/ig,"The $1"); new_content = new_content.replace(/<h2.*? > (. *?) <\/h2>/ig,"The $1"); new_content = new_content.replace(/<h3.*? > (. *?) <\/h3>/ig,"The $1"); new_content = new_content.replace(/<h4.*? > (. *?) <\/h4>/ig,"The $1"); new_content = new_content.replace(/<h5.*? > (. *?) <\/h5>/ig,"The $1"); new_content = new_content.replace(/<h6.*? > (. *?) <\/h6>/ig,"The $1");

   new_content = new_content.replace(/style\="[^"] +"/gi, '');

   alert(new_content);
  $('.testmr').html(new_content);
  }

  $('.testmr').bind('paste',function(e){
   var $this = $(this);
   var original = $this.html(); setTimeout(function(){update(); }, 10); }) }) </script>Copy the code

15. Upload/preview pictures

function updateImage(obj,showid){
	var idFile = $(obj).attr("id"); var docObj = document.getElementById(idFile); var fileName = docObj.value; // Get the fileif(! fileName.match(/.jpg|.gif|.png|.jpeg/i)) { layerOpen('tip'.'The picture you uploaded is not formatted correctly, please select it again! ');
    	return false;
    }
    var imgSrc=' ';
    if/*imgSrc = docobj.files [0].getAsDataUrl (); * /if (window.navigator.userAgent.indexOf("Chrome") >= 1 || window.navigator.userAgent.indexOf("Safari") >= 1) {
    		imgSrc = window.webkitURL.createObjectURL(docObj.files[0]);
    	}
    	else{ imgSrc = window.URL.createObjectURL(docObj.files[0]); }}else {
    	imgSrc= fileName;
    }
    if(navigator.userAgent.indexOf("MSIE 9.0"Var PIC = document.getelementbyId (showid), file = document.getelementbyId (idFile); file.select(); file.blur(); var reallocalpath = document.selection.createRange().text; pic.style.filter ="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src=\"" + reallocalpath + "\")"; // Add filter // set the size of preview PIC here // set img SRC to base64 encoded transparent image undisplay browser default image pic.src ='data:image/gif; base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; } /*var imgUrl = window.URL.createObjectURL(fileList[0]); */ $(obj).next().attr("src",imgSrc);
}

function addAppIndex() {if(! standard_checkInputInfo("addAppForm")) {
		return;
	}
	if(' '= = $('#addAppImg').val()){
		layerOpen('tip'.'Please upload picture');
		return;
	}
	$('#addAppForm').form('submit', {
		url : function() {
			return webPath + '/wechat/homeconfiguration/addHomeconfiguration.htm';
		},
		success : function(data) {
			var dataObj = eval("(" + data + ")");
			if (dataObj.status == 1) {
				$('#addAppForm')[0].reset();
				loadParentAPP(pageNo,quesSize);
				$('.add-app').fadeOut();
				layerOpen('tip',dataObj.msg);
			}else{
				layerOpen('tip',dataObj.msg); }}}); }Copy the code

16. Certain CSS styles

overflow: hidden; / / text-overflow: ellipsis; /** Add ellipsis */ white-space: nowrap; / * * mandatory non-breaking * / word - wrap: normal (the default) |break- word / * interrupt, forced a newline * / word - break: normal (the default) |break-all | keep all / / / * * Firefox, Opera cannot identify * don't let the mouse to select text * / - its - user - select: none. -moz-user-select: none; -ms-user-select: none; user-select: none;Copy the code

17, use JS to judge the operating system, only mobile phone login, and the computer can not log in to the Web

/** * use JS to determine the operating system if it is not a mobile client directly jump to a display page prompt */ <scripttype="text/javascript">
  var ua = window.navigator.userAgent;
  var osVersion = ua.split(";") [2]; var osV = osVersion.substr(osVersion.length - 3, 3); switch (osV) {case "5.0":
    document.write("Win2000");
    break;
  case "5.1":
    document.write("WinXP");
    break;
  case "5.2":
    document.write("Win2003");
    break;
  default:
    document.write("Others");
    break;
  }
</script>Copy the code

18. Wechat JS payment code _ Front-end call wechat payment interface

$(´.save_patient_msg ´).click($(´.save_patient_msg ´).click($(´.save_patient_msg ´).click($(´.save_patient_msg ´) $(´.save_patient_msg ´).click(´.save_patient_msg ´);function(a) {$(´ Save_Patient_Msg ´). Off (´ click ´); var hrdfId = getOrderId(); Var txnAmt = $(´. Sum_pay. The font - red ´). The HTML (); var data = {orderId: hrdfId, txnAmt:"0.01", 
        prodDesc: "Remote Diagnostic Services", callType: "JSAPI",
        access_token: getUrlParam("access_token")}; $.ajax({type: ´ POST ´, url: ´ hims/API/commonPay/queryTransNo? Access_token =´ getUrlParam(´ Access_token ´), dataType:´ JSON ´, contentType:´ Application /json´, data: JSON.stringify(data), success:function(Wxres){
          if(! Wxres){$.alert(´ Server congestion, please visit later ´)}else{
              console.log(Wxres);
              if(Wxres. Data. RespCode = = ´ fail ´) {$. Alert (Wxres. Data. RespMsg); }else{//10 wechat payment interface // 10.1 Initiating a payment request // Note: this Demo uses version 2.7 payment interface. It is recommended to refer to the latest documents related to wechat payment when using this interface. var param = Wxres.data; wx.config({ debug:false// If debug mode is enabled, the return value of all API calls will be displayed in the client side alert. To view the passed parameters, you can open it in the PC side and the parameter information will pass throughlogPrint, print only on PC. AppId: ´ wX403eAD26691402FB ´, // Required, unique identifier of public number timestamp: param.timestamp, // Required, generated signature's timestamp nonceStr: Noncestr,// Required, generates a random string of signatures signature: param.signjs,// Required, calls js signature, jsApiList: [´chooseWXPay´] // Required, list of JS interfaces to use, here only pay}); Wx.choosewxpay ({timestamp: param.timestamp, // Pay signature timestamp, note that all use timestamp fields in wechat JSSDK are lowercase. NonceStr: param. nonceStr, // Payment signature random string, not longer than 32 bits package:"prepay_id="Param.transno, // The prepay_id parameter returned by the unified payment interface. The submission format is as follows: prepay_id=***) signType:"MD5", ´MD5´ paySign: param.sign, // Pay signature success:function (res) {
                            if(res.errMsg == "chooseWXPay:ok"){
                                //alert("Payment successful");
                                window.location.href  = "/hims/weixin/pages/Order_ok.html? access_token=" getUrlParam("access_token");
                            }else{
                                alert(res.errMsg);
                            }
                        },
                        cancel: function(res){//alert(´ Cancel payment ´); }}); } } }, error:function(data){ var msg = data.message || data.status; $. Alert (´ server error ´ MSG); }});return false;
});




functionGetUrlParam (name){// Construct a regular expression object with the target parameters var reg = new RegExp("(^ | &)"  name  "= (/ ^ & *) (& | $)"); / var/match the target parameter r = window. The location, search, substr (1) the match (reg); // Returns the parameter valueif(r! =null)return unescape(r[2]); returnnull; } link: http://dditblog.com/itshare_553.html/http://www.cnblogs.com/kewenxin/p/7463337.html / 2. Wechat payment is mainly composed of three steps: 1. Assemble data to generate pre-payment ID; 2. Result processing $("#getBrandWCPayRequest").click(function() {
    $.ajax({
        type: "POST",
        url: "",
        data: {
            "openId": $("#openId").val(),
            "total_fee": $("#total_price").html(),
            "body": $("#bodydes").html(),
            "productid": $("#productid").val()}, // the argument itself is defined according to the business dataType:"json",
        success: function(data) { callPay(data); }}); });function callPay(data) {
    //alert("Callback execution");  
    var appId = data.appId;
    var timeStamp = data.timeStamp;
    var nonceStr = data.nonceStr;
    var package = data.package;
    var signType = data.signType;
    var paySign = data.paySign;
    //  
    WeixinJSBridge.invoke('getBrandWCPayRequest', {
        "appId": appId,
        "timeStamp": timeStamp,
        "nonceStr": nonceStr,
        "package": package,
        "signType": signType,
        "paySign": paySign

    },
    function(res) {
        //alert(res.err_msg);  
        WeixinJSBridge.log(res.err_msg);
        if (res.err_msg == "get_brand_wcpay_request:ok") {
            //var pc = data.total_fee;  
            //var body = data.body;  
            //var openId = data.openId;  
            //var timeStamp = data.timeStamp;  
            //alert("Transaction Amount :"+pc+"Penny"+"Product Name:"+body+"User openID:"+openId+Order No. :2015+timeStamp);  
            //alert("Payment successful!");  
            WeixinJSBridge.call('closeWindow');
        } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
            //alert("User cancels payment!");  
            //WeixinJSBridge.call('closeWindow');  
        } else {
            alert("Payment failed!");
            WeixinJSBridge.call('closeWindow'); }}); }Copy the code

Blog.csdn.net/yulei_qq/ar… Unionpay blog.csdn.net/Angular_/ar… Mui wechat/Alipay Pay JS

19, copy and paste automatically add source

<script type="text/javascript">
document.body.oncopy = function () {
setTimeout( function () { 
    var text = clipboardData.getData("text"); 
    if (text) { 
        text = text + "\r\n\r\n original address:+location.href; 
        clipboardData.setData("text", text); }}, 100); }; </script>Copy the code

JavaScript automatically adds source when copying and pasting web content:

www.open-open.com/code/view/1420709972656 

outofmemory.cn/code-snippet/633/javascript-fuzhiniantie-wangyeneirong-shi-zidong-augment-chuchu 

Json String and JSON object are exchanged

www.jb51.net/article/350…

JSON.parse(jsonstr); // We can convert json strings into JSON objects json.stringify (jsonobj); // You can convert json objects into JSON string pairsCopy the code

21, Truthy

In JavaScript, Truthy refers to a converted value that is true in a Boolean context. All values are true unless they are defined as falsy (that is, except false, 0, “”, null, undefined, and NaN). JavaScript uses coercion in a Boolean context.

Time formatting

function show(date) {
    var date = new Date(date);
    /*var info = date.getFullYear()+"Year"; */ var info = date.getMonth() + 1 +"Month";
    info += date.getDate() + "Day";
    info += date.getHours() + "When";
    info += date.getMinutes() + "Points";
    return info;
}Copy the code

 moment.js momentjs.cn/ 

23, 30-seconds-of-code code fragment

30-seconds-of-code

Github.com/Chalarangelo/30-seconds-of-code#anagrams-of-string-with-duplicates http://mp.weixin….

Ajax jquery synchronous/asynchronous

Var HTML = $.ajax({url: “some.php”, async: false}).responseText; Or set the Ajax property $.ajaxSetup({async: false}) globally; Post, get is synchronous

25, How to determine the current browser browser?

Extension: How to determine what browser is currently browser?

In short, a list of attributes unique to each browser:

We all know that there are Firefox, Opera, Safari and Chrome. The following is a description of some of the features that are relatively unique to each browser (leaving aside the kernel differences for now, we’ll focus on the relative functions).

Firefox DOM elements have a getBoxObjectFor function that gets the location and size of the DOM element (IE’s equivalent is getBoundingClientRect). This is unique to Firefox and can be checked to see if the current browser is Firefox.

Opera provides a special browser flag, the window.opera property.

Safari has an openDatabase function that is not available in other browsers, which serves as a marker for Safari.

Chrome has a MessageEvent function, but Firefox also has one. Fortunately, Chrome doesn’t have Firefox’s getBoxObjectFor function, so you can still accurately identify Chrome by this criterion.

Byte 1024 conversion method

function bytesToSize(bytes) {  
    if (bytes === 0) return '0 B';  
    var k = 1024, // or 1000  
        sizes = ['B'.'KB'.'MB'.'GB'.'TB'.'PB'.'EB'.'ZB'.'YB'],  
        i = Math.floor(Math.log(bytes) / Math.log(k));  
  
    return (bytes / Math.pow(k, i)).toFixed(1) + ' ' + sizes[i];  
} Copy the code

JS to obtain the URL parameter value (QueryString) 4 methods

Method one: regular method

function getQueryString(name) {
    var reg = new RegExp('(^ | &)' + name + '= (/ ^ & *) (& | $)'.'i');
    var r = window.location.search.substr(1).match(reg);
    if(r ! = null) {return unescape(r[2]);
    }
    returnnull; } // call: alert(GetQueryString()"Parameter Name 1"));
alert(GetQueryString("Parameter Name 2"));
alert(GetQueryString("Parameter Name 3"));Copy the code

Method 2: split the method

function GetRequest() { var url = location.search; // Get the url"?"Var theRequest = new Object();if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    returntheRequest; } var Request = new Object(); Request = GetRequest(); // var parameter 1, parameter 2, parameter 3, parameter N; // Parameter 1 = Request[Parameters' 1 ']; // Parameter 2 = Request[Parameters' 2 ']; // Parameter 3 = Request[Parameters' 3 ']; // N = Request[Parameters' N '];
var q;
q = Request['q'];
q = Request.q;Copy the code

Method three: see re again

function GetQueryString(name) {
    var reg = new RegExp("(^ | &)" + name + "= (/ ^ & *) (& | $)"."i"); var r = window.location.search.substr(1).match(reg); // Get the url"?"String and the re matches var context ="";
    if(r ! = null) context = r[2]; reg = null; r = null;return context == null || context == "" || context == "undefined" ? "": context;
}
alert(GetQueryString("q"));Copy the code

Method 4: obtain method of single parameter

function GetRequest() { var url = location.search; // Get the url"?"The string following the characterif (url.indexOf("?")! Var STR = url.substr(1); var STR = url.substr(1); // Start with the first character because the 0th character is? STRS = str.split(STRS = str.split("="); Alert (STRS [1]); alert(STRS [1]); // Pop the first argument (loop if there are multiple arguments)}}Copy the code

28. Get browser version information

function getBroswer(){
    var sys = {};
    var ua = navigator.userAgent.toLowerCase();
    var s;
    (s = ua.match(/edge\/([\d.]+)/)) ? sys.edge = s[1] :
    (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? sys.ie = s[1] :
    (s = ua.match(/msie ([\d.]+)/)) ? sys.ie = s[1] :
    (s = ua.match(/firefox\/([\d.]+)/)) ? sys.firefox = s[1] :
    (s = ua.match(/chrome\/([\d.]+)/)) ? sys.chrome = s[1] :
    (s = ua.match(/opera.([\d.]+)/)) ? sys.opera = s[1] :
    (s = ua.match(/version\/([\d.]+).*safari/)) ? sys.safari = s[1] : 0;

    if (sys.edge) return { broswer : "Edge", version : sys.edge };
    if (sys.ie) return { broswer : "IE", version : sys.ie };
    if (sys.firefox) return { broswer : "Firefox", version : sys.firefox };
    if (sys.chrome) return { broswer : "Chrome", version : sys.chrome };
    if (sys.opera) return { broswer : "Opera", version : sys.opera };
    if (sys.safari) return { broswer : "Safari", version : sys.safari };
    
    return { broswer : "", version : "0" };
}	
getBroswer();Copy the code

29, firefox hacks

@-moz-document url-prefix(){.input2{top:2px; }}Copy the code

Json js object JS string conversion

 jquery-json 

var thing = {plugin: 'jquery-json'Version: 2.3}; Var encoded = $.tojson (thing); // Convert to json, resulting in:'{" plugins ":" jquery - json ", "version" : 2.3}'var name = $.evalJSON( encoded ).plugin; //js object. Property, result:"jquery-json"var version = $.evalJSON(encoded).version; // Result: 2.3Copy the code

31, avoid the browser auto-fill form solution

www.cnblogs.com/moonLightcy…

1. Add an Input hide box to fill it

<input name="old-userName" type="text">
<input name="old-pwd" type="password">
<ul class="ul-info"<li><label> Account: </label> <input ID ="userName" type="text"</li> <li><label> Password: </label> <input class="0" type="password">
    </li>
</ul> Copy the code

2. Modify the selector

<li><label> Account: </label> <input ID ="a" type="text"</li> <li><label> Password: </label> <inputtype="password">
</li> Copy the code

This way is my own idle, boring, trying to play to try out, feel this way is more reasonable, after all, DOM is so expensive, do not need extra input, this way need to pay attention to several points are:

Type =’text’;

2), type=’password’ can not have id or name (either will cause autofill), can have class;

3) Visually, this approach does not work on 360, Google has no problem, cautious;

3. Use JS control

One additional tip: If you just want to remove the yellow background and keep the filled value, you can do either of the following CSS styles, because the style you are changing is not in the user agent style sheet.

input:-webkit-autofill { -webkit-box-shadow: 0 0 0 1000px white inset ! important; } input:-webkit-autofill { transition: background-color 5000s ease-in-out 0s; }Copy the code

32. Synthesis of interview questions

Juejin. Cn/post / 684490… https://juejin.cn/post/6844903465886416910 https://juejin.cn/post/1 https://juejin.cn/post/6844903508810940429

33. Add meta to the HTML header to convert all resource requests from HTTP to HTTPS

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">Copy the code

34. Set the browsing mode of the dual-core browser

<meta name="renderer" content="webkit|ie-comp|ie-stand"> 

The value of content is one of WebKit, IE-comp, and IE-Stand, which are case sensitive and represent webKit kernel, IE compatible kernel, and IE standard kernel respectively.


The highest version of IE

<meta http-equiv="X-UA-Compatible" content="IE=EDGE"> Copy the code

36, both ends of the use of alignment

www.cnblogs.com/reaf/p/6795…

Methods in links are more comprehensive

<style>
    p{
        margin: 0;
        font-size: 12px;
    }
    .justify{
        text-align: justify;
        height: 20px;
        width:50px;
    }
    .justify:after{
        content:'. ';
        width: 100%;
        display: inline-block;
        overflow: hidden;
        height: 0;
    }
</style><body>
<div style="width: 150px;">
    <div style="overflow: hidden;">
        <p class="justify" style="float: left;"<p style= "max-width: 100%; clear: both; min-height: 1em"float: left;""> : 2018-10-19</p> </div> <div style="overflow: hidden;">
        <p class="justify" style="float: left;""> <p style=" max-width: 100%; clear: both; min-height: 1em"float: left;"2018-10-19</p> </div> </div> </body>Copy the code

The above code tested under Google can IE does not support

37. Printing function related

1. Solve the problem that Webkit browser needs to manually set “print background color” when printing web pages: For example, if an element has a background color, the default browser does not print the background image and background color when printing. To print, add the following code to the element’s style: -webkit-print-color-adjust: exact; The background image and color will be printed whether “Print background and color” is checked or not in the WebKit browser. IE is invalid

38. Block the browser back button

window.history.pushState('aa', document.URL);
window.addEventListener('popstate'.function () {
	history.pushState('aa', document.URL);
}, false);Copy the code