前端小知识

一、input 框限制

1. 只能输入数字代码(小数点也不能输入)

<input onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')">

2. 只能输入数字,能输小数点

<input onkeyup="if(isNaN(value))execCommand('undo')" onafterpaste="if(isNaN(value))execCommand('undo')">
<input name="txt1" οnchange="if(/\D/.test(this.value)){alert('只能输入数字');this.value='';}">

3. 只能输入英文字母和数字,不能输入中文

<input onkeyup="value=value.replace(/[^\w\.\/]/ig,'')">

4. 小数点后只能有最多两位(数字,中文都可输入),不能输入字母和运算符号

<input onkeypress="if((event.keyCode<48 || event.keyCode>57) &amp;&amp; event.keyCode!=46 || /\.\d\d$/.test(value))event.returnValue=false">

5. 数点后只能有最多两位(数字,字母,中文都可输入),可以输入运算符号

<input onkeyup="this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')">

6. 输入数字

<input type="text" onkeyup="this.value=this.value.replace(/\D/g,'')"> 

7. 输入中文

<input type="text" onkeyup="this.value=this.value.replace(/[^\u4e00-\u9fa5]/g,'')"> 

8. 输入英文

<input type="text" onkeyup="this.value=this.value.replace(/[^a-zA-Z]/g,'')"> 

9. 只输入数字和字母

<input class="input" maxlength="12" size="15" name="username" id="username" οnkeyup="value=value.replace(/[\W]/g,'')">

二、下拉框相关

1. 实时获取下来选项做出显示判断

<label>报名组别:<span style="color: red;"> *</span></label>
<div class="item item-password">
     <select class="txt-input txt-username RegistrationGroup" id="RegistrationGroup">
          <option value="">请选择...</option>
          <option value="混合团体赛">混合团体赛</option>
          <option value="嘉宾赛">嘉宾赛</option>
     </select>
</div>
<div class="Project"> <label>项目名称:<span style="color: red;"> *</span></label> <div class="item item-password"> <select class="txt-input txt-username ProjectName" id="ProjectName"> </select> </div> </div> <div class="IntimateYC"> <label>搭档:<span style="color: red;"> *</span></label> <div class="item item-username"> <input id="Intimate" class="txt-input txt-username" type="text" placeholder="例:张三" value="" name="Intimate" autocomplete="off" onkeyup="this.value=this.value.replace(/[^\u4e00-\u9fa5]/g,'')" /> </div> </div>
.Project {
     display: none;
}
.IntimateYC {
    display: none;
}
<script>
    /*控制可报名的项目名称*/
    var RegistrationGroupSS = document.getElementById("RegistrationGroup");
    RegistrationGroupSS.onchange = function () {
        if (RegistrationGroupSS.options[RegistrationGroupSS.selectedIndex].value == '') {
       $('.IntimateYC').hide(); $(
'.Project').hide(); } else if (RegistrationGroupSS.options[RegistrationGroupSS.selectedIndex].value != '') { $('.Project').show(); if ($("#RegistrationGroup").val() == "嘉宾赛") { $("#ProjectName").empty(); let arr = ['请选择..', '男双', '女双', '混双'] let com = document.getElementById("ProjectName"); for (let i = 0; i < arr.length; i++) { com.options.add(new Option(arr[i], arr[i])); } } else { $("#ProjectName").empty(); let arr = ['请选择..', '男双', '女双', '混双', '青年男单', '中年男单'] let com = document.getElementById("ProjectName"); for (let i = 0; i < arr.length; i++) { com.options.add(new Option(arr[i], arr[i])); } } } } /*实时获取选中的项目名称,根据项目名称判断是否需要‘搭档’字段输入*/ var selects = document.getElementById("ProjectName"); selects.onchange = function () { if ((selects.options[selects.selectedIndex].value).indexOf("双") !== -1) { $('.IntimateYC').show(); } else { $('.IntimateYC').hide(); } } </script>
注意:一定要使用‘onchange’哦,不要用‘onclick’或者别的哦~要不然你会发现一个小Bug哦~

三、按钮倒计时

<!DOCTYPE html>
<html>
<head>
<title>Laugh“【按钮倒计时】</title>
</head>
<body>
    <input type="button" id="testList" value="获取验证码" />
</body>
    <script type="text/javascript">
        var countdown = 5;
        var id;
        function setTime(targetElement) {
            if (countdown == 0) {
                targetElement.removeAttribute("disabled");
                targetElement.value = "获取验证码";
                countdown = 5;
                clearTimeout(id);//关闭定时执行函数
            } else {
                targetElement.setAttribute("disabled", true);
                targetElement.value = "重新发送(" + countdown + "s)";
                countdown--;
                id = setTimeout(function () { setTime(targetElement) }, 1000);
            }
        }
        document.getElementById("testList").onclick = function () { setTime(this); }
    </script>
</html>

四、图片压缩

4.1):前端js

var uploadListIns = upload.render({
    elem: '#testList',
    elemList: $('#demoList'),
    url: '../Ajax/Layui_FileUpload.ashx',
    accept: 'file',
    multiple: true,
    number: 3,
    auto: true,
    before: function (obj) {
         console.log(obj);
    },
    choose: function (obj) {
    var that = this;
    var files = this.files = obj.pushFile();
    //读取本地文件
    obj.preview(function (index, file, result) {
    tr = $(['<tr id="upload-' + index + '">'
    , '<td>' + timestamp + '' + file.name + '</td>'
    , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
    , '<td><div class="layui-progress" lay-filter="progress-demo-' + index + '"><div class="layui-progress-bar" lay-percent=""></div></div></td>'
    , '<td>'
    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide" style="border:1px solid #d0c9c2;">重传</button>'
    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete" style="border:1px solid #d0c9c2;">删除</button>'
    , '</td>'
    , '</tr>'].join(''));

    //单个重传
    tr.find('.demo-reload').on('click', function () {
       obj.upload(index, file);
    });

    //删除
    tr.find('.demo-delete').on('click', function () {
    delete files["upload-" + index];
    delete Filess[index];
    dell("upload-" + index);
         uploadListIns.config.elem.next()[0].value = '';
    });

      that.elemList.append(tr);
      element.render('progress');
    });
    }
    , done: function (res, index, upload) {
    //成功的回调
    var that = this;
    var tr = that.elemList.find('tr#upload-' + index), tds = tr.children();
    Filess[index] = res.data.src;
    console.log(res.data.src);

    delete this.files[index]; //删除文件队列已经上传成功的文件
        return;
        this.error(index, upload);
    }
    , allDone: function (obj) { //多文件上传完毕后的状态回调
         console.log(obj)
    }
    , error: function (index, upload) { //错误回调
         var that = this;
         var tr = that.elemList.find('tr#upload-' + index)
             , tds = tr.children();
              tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
     }
     , progress: function (n, elem, e, index) { //注意:index 参数为 layui 2.6.6 新增
             element.progress('progress-demo-' + index, n + '%'); //执行进度条。n 即为返回的进度百分比
     }
});

4.2):后端

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace kmvc.WEB.Ajax
{
    /// <summary>
    /// Layui_FileUpload 的摘要说明
    /// </summary>
    public class Layui_FileUpload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write(Save());
        }
        public string Save()
        {
            try
            {
                HttpPostedFile file = HttpContext.Current.Request.Files["file"];
                string localname = file.FileName;
                if (localname.IndexOf("\\") != -1)
                {
                    string[] a = localname.Split('\\');
                    localname = a[a.Length - 1];
                }
                string file1 = Path.GetFileNameWithoutExtension(localname);//获取上传文件名字 不获取后缀名
                //处理文件的异常符号
                file1 = file1.Replace("+", "_").Replace("/", "_").Replace("", "_").Replace("", "_");
                //获取文件名后缀
                string wjhz = Path.GetExtension(localname);   //获取文件后缀名 aspx
                Random random = new Random(DateTime.Now.Millisecond);
                string sfilename = DateTime.Now.ToString("yyyyMMdd");//获取当前年月
                string sfilenameYaSuo = "YaSuo" + DateTime.Now.ToString("yyyyMMddHHmmssfff");//获取当前年月日时分秒毫秒
                //更改文件名
                //string filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + GetFileExt(localname);
                string filename = file1 + wjhz;//拼接 获取的“文件名”和文件“后缀”
                //获得文件保存路径
                string FilePath = HttpContext.Current.Request.MapPath("../UploadFileNew/" + sfilename);
                //压缩保存路径
                string FilePathYaSuo = HttpContext.Current.Request.MapPath("../UploadFileNew/" + sfilenameYaSuo);
                CreateFolder(FilePath);//创建文件夹
                CreateFolder(FilePathYaSuo);//创建文件夹 压缩后图片存储
                if (file != null)
                {
                    //不存在则创建文件路径 正常图片存在路径
                    if (!Directory.Exists(FilePath))
                    {
                        Directory.CreateDirectory(FilePath);
                    }
                    //不存在则创建文件路径 压缩图存在路径
                    if (!Directory.Exists(FilePathYaSuo))
                    {
                        Directory.CreateDirectory(FilePathYaSuo);
                    }
                    //file.SaveAs(uploadpath + filename);
                    FilePath = FilePath + "\\" + filename;//文件的保存路径   本地路径FilePath + 下载文件名filename
                    file.SaveAs(FilePath);//可理解为 映射网络启动器 并保存 
                    FilePath = FilePath.Replace("\\", "/"); 

                    FilePathYaSuo = FilePathYaSuo + "\\" + filename;//文件的保存路径   本地路径FilePath + 下载文件名filename
                    file.SaveAs(FilePathYaSuo);//可理解为 映射网络启动器 并保存 
                    FilePathYaSuo = FilePathYaSuo.Replace("\\", "/");
                    FileInfo firstFileInfo = new FileInfo(FilePath);
                    if (firstFileInfo.Length > 300 * 1024) {
                        LaughCompressImage(FilePath, FilePathYaSuo);
                    }
                    string returnstring = "/UploadFileNew/" + sfilenameYaSuo + "/" + filename;
                    return "{  \"code\": 0  ,\"msg\": \"\"  ,\"data\": { \"src\": \""+ returnstring + "\"  } } ";
                }
                else
                {
                    return "{\"error\":\"加载数据失败:" + " " + "\"}";
                }
            }
            catch { return ""; }
        }
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片地址</param>
        /// <param name="dFile">压缩后保存图片地址</param>
        /// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
        /// <param name="size">压缩后图片的最大大小</param>
        /// <param name="sfsc">是否是第一次调用</param>
        /// <returns></returns>
        public static bool LaughCompressImage(string sFile, string dFile, int flag = 90, int size = 300, bool sfsc = true)
        {
            //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
            FileInfo firstFileInfo = new FileInfo(sFile);
            if (sfsc == true && firstFileInfo.Length < size * 1024)
            {
                firstFileInfo.CopyTo(dFile);
                return true;
            }
            Image iSource = Image.FromFile(sFile); ImageFormat tFormat = iSource.RawFormat;
            int dHeight = iSource.Height / 2;
            int dWidth = iSource.Width / 2;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);
            if (tem_size.Width > dHeight || tem_size.Width > dWidth)
            {
                if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);
            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
            g.Dispose();

            //以下代码为保存图片时,设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;

            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                    FileInfo fi = new FileInfo(dFile);
                    if (fi.Length > 1024 * size)
                    {
                        flag = flag - 10;
                        LaughCompressImage(sFile, dFile, flag, size, false);
                    }
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }
    }
}

五、转中文乱码

5.1):HTML代码:

{
display: '合同编号', name: '合同编号', align: 'centen', height: 27, width: 170, frozen: true,
render: function (rowdata, rowindex, value) {
     return "<a style='color:green;font-weight:800;' href='javascript:void()' onclick=\"ProjectSchedule('" + rowdata.合同编号 + "','" + rowdata.合同状态 + "','" + rowdata.地市 + "','" + rowdata.项目金额 + "','" + rowdata.客户经理 + "','" + rowdata.STATE + "','" + rowdata.售中 + "','" + rowdata.售后 + "','" + rowdata.合同标题 + "')\"  >" + rowdata.合同编号 + "</a>";
     }
},

5.2):JS代码:

//流程进度
function ProjectSchedule(HTBH, HTZT, XMDS, XMJE, KHJL, STATE, InSale, AfterSale, ContractTitle) {
    layer.open({
        type: 2,
        title: '合同编码:【' + escape(HTBH) + '】;项目状态:【' + decodeURI(HTZT) + '】;项目地市:【' + decodeURI(XMDS) + '】;客户经理:【' + decodeURI(KHJL) + '】 ;',
        resize: true,
        area: ['99%', '97%'],
        content: 'LiangYi_LiuChengJinDu.html?V_HTBM=' + escape(HTBH) + '&V_XMJE=' + decodeURI(XMJE) + '&V_KHJL=' + decodeURI(KHJL) + '&V_STATE=' + escape(STATE) + '&V_InSale=' + escape(InSale) + '&V_AfterSale=' + escape(AfterSale) + '&V_ContractTitle=' + escape(ContractTitle)
        , success: function (layero, index) {
            layero.addClass('layui-form');
            layero.find('.layui-layer-btn0').attr({
                'lay-filter': 'demo1',
                'lay-submit': ''
            });
        },
        yes: function (index, layero) { 
            var iframeWin = window[layero.find('iframe')[0]['name']];
            console.log(iframeWin);
            var flag = iframeWin.mySubmit(index);
        }
        , btn2: function (index, layero) {
            layer.close(index);
        }
    });
}

5.3):新页面解析JS

var url = document.location.toString(); //获取url地址
var urlParmStr = url.slice(url.indexOf('?') + 1); //获取问号后所有的字符串
var arr = urlParmStr.split('&'); //通过&符号将字符串分割转成数组
var V_HTBM = arr[0].split("=")[1]; //第一个参数
var V_XMJE = arr[1].split("=")[1]; //第二个参数
var V_KHJL = arr[2].split("=")[1]; //第三个参数
var V_STATE = arr[3].split("=")[1]; //第四个参数
var V_InSale = arr[4].split("=")[1]; //第五个参数
var V_AfterSale = arr[5].split("=")[1]; //第六个参数
var V_ContractTitle = arr[6].split("=")[1]; //第六个参数

5.3.1):转码方式:

unescape(V_ContractTitle.replace(/\\/g, "%"))

 

posted @ 2024-01-25 11:26  Laugh"  阅读(85)  评论(0编辑  收藏  举报