javascript經常使用小案例

經常使用javascript小案例

樣式調節

//注: 這個能夠控制td中的字段成行顯示     
#modelInfos td,th {  white-space: nowrap;   }

//文本輸入框隨着內容尺寸往下變大,在input框中加入這兩個屬性,而後就能夠控制文本輸入框的大小尺寸隨着內容而變
onpropertychange="this.style.height=this.scrollHeight + 'px'" 
oninput="this.style.height=this.scrollHeight + 'px'"

點擊radio 選擇一整行(這種寫法不太靠譜,能夠試試)

style="cursor: hand" 
bgcolor="<%=(obj.getState() == 0 ? trColor : obj.getState() == 1 ? '#FFCC33' : '#FF8040')%>"  onclick="selectRow(<%=i%>,this);"

// 注: 另外一種寫法 雙擊選中一行[單擊不能夠
$(function(){
    var screenSize = window.screen.width-200;
    var div1 = document.getElementById('pool');    
    div1.style.width = screenSize;  
    $('tr').dblclick(function(){
       $td = $(this).find("td:eq(0)").find("input[type=radio]").attr("checked", true);
       var varId = $(this).attr("id");
       if($(this).attr("id").length>3){
           var str = varId.substr(0,3);
           if(str=='row'){
              startDealTask();  
           }
       }
       return false;
    });
})

當前條件所在的行的顏色爲紅色

$("tr",$("#gxzItems")).each(function(){
	var itemFlag=$("input[name='flagTY']",$(this)).val();
	if(itemFlag=='0'){
		$("td", $(this)).css({"color":"red"});
	}
});

格式化金額

<fmt:formatNumber pattern="#,##0.00#" value="${pto1.map.tradeAmt}" />

寫彈窗(標題div中須要加入的樣式)

style="display: none; z-index: 9997; border-width: 1px; border-style: solid; border-color: navy; position: absolute; left: 250px; top: 103px; background-color: #ffffff; width: 350px; height: 115px; filter: progid :DXImageTransform.Microsoft.Shadow(color =#999999, direction =135, strength = 5);"

支持拖拽

oTitle.onmousedown=function(event){ 
    oTitle.style.cursor = "move"; 
     var event = event || window.event; 
     var disX=event.clientX-oDrag.offsetLeft; 
     var disY=event.clientY-oDrag.offsetTop; 
     
     // 鼠標移動,窗口隨之移動,  onmousemove在有物體移動是才執行alert事件;  
	 document.onmousemove=function(event){ 
         var event = event || window.event; 
         maxW=document.documentElement.clientWidth-oDrag.offsetWidth; 
         maxH=document.documentElement.clientHeight-oDrag.offsetHeight; 
         posX=event.clientX-disX; 
         posY=event.clientY-disY; 
         if(posX<0){ 
             posX=0; 
         }else if(posX>maxW){ 
             posX=maxW; 
         } 
         if(posY<0){ 
             posY=0; 
         }else if(posY>maxH){ 
             posY=maxH; 
         } 
         oDrag.style.left=posX+'px'; 
         oDrag.style.top=posY+'px'; 
     } 
     //鼠標鬆開,窗口將再也不移動 , document.onmouseup=function(){ 
         document.onmousemove=null; 
         document.onmouseup=null; 
     } 
 }

測試用戶點擊關閉瀏覽器,事件回到數據庫中執行一條語句

<script type="text/javascript"
	src="<c:url value='/js/jquery-1.8.3.js'/>"></script>
<script>
	window.onbeforeunload = function() //author: meizz 
	{
		var n = window.event.screenX - window.screenLeft;
		var b = n > document.documentElement.scrollWidth - 20;
		if (b && window.event.clientY < 0 || window.event.altKey) {
			$.ajax({
				url : "/demo03/itemModel/onbeforeload",
				async : false,
				success : function() {
					alert("不可能");
				}
			});
		}
	}
</script>

提交點擊提交form表單值, 則能夠將結果顯示在當前頁面的iframe內聯框中, 實現頁面局部刷新

<form id="organManageForm" name="organManageForm" style="width: 30%"
			action="<%=com.northking.ssoClient.bussiness.impl.Parameters.pathPrefix%>servlet/SmOrganListServlet" method="post" target="frmdetail">
	</form>
	</div>
	</td>
	<td width="50%" style="vertical-align: top">
	<div id="floater" style="position:absolute; height=300">
	<iframe name="frmdetail" class="" frameborder=0 style="width: 100%;height:100%;background-color:  #eeeeee;"></iframe>
	</div>

圖片響應流到頁面展現, filepath = ""圖片路徑";

response.setContentType("image/jpeg");
ServletOutputStream out=response.getOutputStream();
	try {	  
		     File file = new File(filePath);
		     FileImageInputStream imageinput = new FileImageInputStream(file);
		     int data;
	         while((data=imageinput.read())!=-1)
	         {
	        	 out.write(data);
	         }
	         imageinput.close();
	  } catch (Exception e) {
		 logger.error(e);   
	  }finally{		     
		  out.flush();
		  out.close();
  }

使用js寫COOKIE

<script type="text/javascript">
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
return ""
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}

function checkCookie()
{
username=getCookie('username')
if (username!=null && username!="")
  {alert('Welcome again '+username+'!')}
else 
  {
  username=prompt('Please enter your name:',"")
  if (username!=null && username!="")
    {
    setCookie('username',username,365)
    }
  }
}
</script>
<body onLoad="checkCookie()">

常知小技巧

  • 對於任何類型的值採用雙not ,能夠獲得其真正的boolean類型值 . 寫法: if(!!cont){} [注: 有值就表示true , 沒值或爲false或爲0就返回false]javascript

  • null 與 undefined 是相等的 if(null == undefined) { 返回true } , [注: 非全等號由感嘆號加兩個等號(!==)表示,只有在無需類型轉換運算數不相等的狀況下,才返回 true。]css

  • start : i = 5; 能夠以這樣的方式給語句加個標籤, 方面下面調用.html

  • js中文轉碼: encodeURI(encodeURI( //須要轉碼的內容 ))java

  • 要想實現點擊下拉框, 選中內容在文本框中顯示, 而且支持多選 , 請百度搜索 multiple-selectjquery

  • 使用這種函數 var formData=$("form").serialize(); ,能夠獲取form表單中的參數和值, 以 name=2&pass=3的 形式鏈接到一塊ajax

arguments[0] .length 這些能夠寫在函數內部, arguments是系統命名的獲取傳進函數的變量的值的數組集合 , 能夠不用聲明,直接在函數內部使用,而只須要調用是傳參數就行

<a  href="javascript:void(0);"  onclick="sayHi('',null,undefined)">點擊這裏,調用函數</a>
 </body>
 <script tyee="text/javascript">
    function sayHi() {
          var  num=arguments.length;
	     if (num != 0) {//調用傳參函數
	        if(num==1){//調用傳一個參函數
	        
	           alert("1個參數");
	        }else  if(num==2){//調用傳2個參函數
	        
	           alert("2個參數");
	        }else if(num==3){//調用傳3個參函數
	        
	           alert("3個參數");
	        }else{//調用傳其餘參函數
	        
	           alert("3個以上參數");
	        }
	    }else {//調用無參函數
	    
	        alert("你沒有往該函數裏面傳入任何值!!!");
	    }
	}
	// 注: 能夠使用函數名.length, 來獲取該函數傳入參數的個數.
 </script>

在函數中使用閉包 , 內部函數不能傳參, 但能夠使用外部的一切變量.

var iBaseNum = 10;
function addNum(iNum1, iNum2) {
  function doAdd() {
  	  return iNum1 + iNum2 + iBaseNum;
  }
  return doAdd();
}

圖像操做. (詳細請看附加圖像文件) ( )

// 圖像 旋轉 的函數
var irotation = 1;
function rotation()
{
   document.all.IFramePic1.style.filter ="progid:DXImageTransform.Microsoft.BasicImage(rotation="+ irotation  +")";
   irotation++;
   if(irotation>4)
      {
          irotation=1;
      }
}

使用js獲取上月最後一天日期

<script type="text/javascript">
  $(function(){
     var   endAccountDate = document.getElementById("endAccountDate").value;
     if(endAccountDate==null||endAccountDate==''){
    	         var nowdays = new Date();
    var year = nowdays.getFullYear();
    var month = nowdays.getMonth();
    if(month==0)
    {
        month=12;
        year=year-1;
    }
    if (month < 10) {
        month = "0" + month;
    }
    var firstDay = year + "-" + month + "-" + "01";//上個月的第一天
    var myDate = new Date(year, month, 0);
    var lastDay = year + "-" + month + "-" + myDate.getDate();//上個月的最後一天
      }
  });
function Appendzero(obj) {  
    if(obj<10) return "0" +""+ obj;  
    else return obj;  
}
function resolveDayDate(begin_Date,end_Date){
	var beginDate = new Date(begin_Date.substring(0,4),begin_Date.substring(4,6)-1,begin_Date.substring(6,8));
	var endDate = new Date(end_Date.substring(0,4),end_Date.substring(4,6)-1,end_Date.substring(6,8));
	beginDate.setDate(beginDate.getDate()+31);
	return beginDate.getTime() >= endDate.getTime();
} 
function resolveMonthDate(begin_Date,end_Date){
	var beginDate = new  Date(begin_Date.substring(0,4),begin_Date.substring(4,6)-1,begin_Date.substring(6,8));
	var endDate = new Date(end_Date.substring(0,4),end_Date.substring(4,6)-1,end_Date.substring(6,8));
	beginDate.setMonth(beginDate.getMonth()+12);
	return beginDate.getTime() >= endDate.getTime();
} 
</script>

獲取當前日期上月最後一天

$(function(){
         var fl=$("#fl").val();
         if(fl=='0'){
            var  endDate=$("input[name='endAccountDate']").val();
            var  ss=ff(endDate);
            $("input[name='startAccountDate']").val(ss);
          }
    });
function  ff(endDate){
    var  month =  endDate.substr(4,2);
    var  year = endDate.substr(0,4);
    if(month=='01'){
         month = 12;
         year -=1;
     }else{
         month -=1;
         }
    var day = new Date(year, month, 0).getDate();
    return   year+""+Appendzero(month)+""+Appendzero(day);
}
function Appendzero(obj)  {  
    if(obj<10) return "0" +""+ obj;  
    else return obj;  
}

內容相對於滾動條位置不動

$(function(){
	var screenSize = window.screen.width-200;
	var div1 = document.getElementById('pool');    
	div1.style.width = screenSize;	
});
<div id="pool" style="overflow: auto;"> 
      //要優化的內容
</div>

懸浮動態走馬燈

<marquee style="WIDTH: 100%; HEIGHT: 400px" scrollamount="3"
	direction="up"> <span style="color: red; font-size: 20px;"><strong>頁面維護中..</strong></span>
</marquee>

下拉框多選[select] , 在下拉框中添加 multiple="multiple" 屬性

// js代碼
function  subbmit(){
	var all = ""; 
	 $("select[name='orgId'] option").each(function() { 
		    all += $(this).attr("value")+" "; 
	 }); 
	 var sel = $("select[name='orgId']").val(); 
	 alert("多選列表全部的值是:  " + all + "其中被選中的是"+sel+"。); 
}

使用javascript操做excel

<!DOCTYPE HTML>
<html>
    <head>
        <title>
            New Document
        </title>
        <meta name="Generator" content="EditPlus">
        <meta name="Author" content="">
        <meta name="Keywords" content="">
        <meta name="Description" content="">
        <script type="text/javascript">
        	  var array1 = [];
            var arr;
            function WriteExcel() {
                var tempStr = "";
                //獲得文件路徑的值  
                var filePath = document.getElementById("upfile").value;
                //建立操做EXCEL應用程序的實例  
                try {
                    var oXL = new ActiveXObject("Excel.application");
                } catch(e) {
                    alert("請啓用ActiveX控件設置!");
                    return;
                }
                //打開指定路徑的excel文件  
                var oWB = oXL.Workbooks.open(filePath);
                //操做第一個sheet(從一開始,而非零)  
                oWB.worksheets(1).select();
                var oSheet = oWB.ActiveSheet;
                //使用的行數  
                var rows = oSheet.usedrange.rows.count;
                try {
                    for (var i = 1; i <= rows; i++) {
                        var obj = new Object();
                        obj.seq =    oSheet.Cells(i,1).value; 
												obj.jgmc=    oSheet.Cells(i,2).value;  
												obj.wdmc=    oSheet.Cells(i,3).value;  
												obj.wddm=    oSheet.Cells(i,4).value;  
												obj.ywpz=    oSheet.Cells(i,5).value;  
												obj.hdmx=    oSheet.Cells(i,6).value;  
												obj.cccy=    oSheet.Cells(i,7).value;  
												obj.cccyfb=  oSheet.Cells(i,8).value;  
												obj.sjkm=    oSheet.Cells(i,9).value;  
												obj.cclx=    oSheet.Cells(i,10).value; 
												obj.cccjrq=  oSheet.Cells(i,11).value; 
												obj.ywrq=    oSheet.Cells(i,12).value; 
												obj.ccy=     oSheet.Cells(i,13).value; 
												obj.sjje=    oSheet.Cells(i,14).value; 
												                                       
                        array1.push(obj);
                        obj=null;
                    }
                    arr =   JSON.stringify(array1);
                } catch(e) {
                    document.getElementById("txtArea").value = "出錯了";
                }
                document.getElementById("txtArea").value = arr;
                //退出操做excel的實例對象  
                oXL.Application.Quit();
                //手動調用垃圾收集器  
                CollectGarbage();
            }
            function   ReadExcel(){
            	alert(array1[1].jgmc); 
            }
        </script>
    </head>
    <body>
        <input type="file" id="upfile" />
        <input type="button" onclick="WriteExcel();" value="write">
         <input type="button" onclick="ReadExcel();" value="read">
        <br>
        <textarea id="txtArea" cols=200 rows=400>
        </textarea>
    </body>
</html>

未完待續, 後續補充中。。。。。數據庫

相關文章
相關標籤/搜索