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]

  • null 与 undefined 是相等的 if(null == undefined) { 返回true } , [注: 非全等号由感叹号加两个等号(!==)表示,只有在无需类型转换运算数不相等的情况下,才返回 true。]

  • start : i = 5; 可以以这样的方式给语句加个标签, 方面下面调用.
  • js中文转码: encodeURI(encodeURI( //需要转码的内容 ))
  • 要想实现点击下拉框, 选中内容在文本框中显示, 并且支持多选 , 请百度搜索 multiple-select
  • 使用这种函数 var formData=$("form").serialize(); ,可以获取form表单中的参数和值, 以 name=2&pass=3的 形式连接到一块

    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>

未完待续, 后续补充中。。。。。

转载于:https://www.cnblogs.com/eian/p/11478489.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值