我的常用代码

将富文本中的图片设置为宽度100%

formatRichText(html) { //控制小程序中图片大小
      let newContent = ''
      if (typeof(html) == 'string') { //检测值为字符串才能进行replace操作
        newContent = html.replace(/<img[^>]*>/gi,
        function(match) {
          match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
          match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
          match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
          return match;
        });
        newContent = newContent.replace(/style="[^"]+"/gi,
        function(match) {
          match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
          return match;
        });
        newContent = newContent.replace(/<br[^>]*\/>/gi, '');
        newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
        return newContent;
      }
    },

判断json字符串为json格式

isJSON(str) {
  if (typeof str === 'string') {
      try {
        JSON.parse(str);
        return true
      } catch(e) {
        return false
      }
  }
},

递归处理数据

function traverse(obj){
  for(var i in obj){
    if(obj[i].children){
      traverse(obj[i].children)
    }
    if(!obj[i].children.length){
      delete obj[i].children;
    }
  }
}

判断对象是否为空

JSON.stringify(data) == "{}"

去掉html标记

str.replace(/<[^>]+>/g,"")

获取URL参数

function getQueryVariable(variable){
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

获取地址栏信息

function getParameter(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]); return null;
}

监听输入框

$('.demoClass').bind('input propertychange', function() {});

隐藏滚动条

.noScroll{
  // background: red;
  -ms-overflow-style: none;
  overflow: -moz-scrollbars-none;
  &::-webkit-scrollbar{
      width: 0px;
  }
}

禁用鼠标右键

document.onselectstart = function(){
    event.returnValue = false;
}

输入框title动态展示

	<div class="input-fill-x">
      <input class="input-fill" placeholder="邮箱">
      <label class="input-label">邮箱</label>
    </div>

<style>
      .input-fill-x{
        position: relative;
        margin-top: 100px;
      }
      .input-fill{
        height: 50px;
        padding: 0 10px;
        outline: none;
        border: 1px solid #d0d0d5;
        border-radius: 4px;
        transition: border-color .3s;
        font-size: 18px;
        color: #333333;
      }
      .input-label{
        background: #ffffff;
        position: absolute;
        left: 10px;
        top: 15px;
        pointer-events: none;
        transition: 0.3s;
        color: #a2a9b6;
      }
      
      .input-fill:placeholder-shown::placeholder{ /* 将placeholder消失 */
        color: transparent; 
      }

      .input-fill:not(:placeholder-shown)~.input-label, /* 鼠标点击输入框 */
      .input-fill:focus ~ .input-label{
        transform: scale(0.85) translate(0, -32px);
        padding: 0 3px;
        color: #1890ff;
      }

      .input-fill:not(:placeholder-shown),
      .input-fill:focus{
        border: 2px solid #1890ff;
      }
    </style>

加载中显示三个点点

<a href="javascript:" class="grebtn">订单提交中<span class="dotting"></span></a>


.dotting {
    display: inline-block; width: 10px; min-height: 2px;
    padding-right: 2px;
    border-left: 2px solid currentColor; border-right: 2px solid currentColor;
    background-color: currentColor; background-clip: content-box;
    box-sizing: border-box;
    -webkit-animation: dot 4s infinite step-start both;
    animation: dot 4s infinite step-start both;
    *zoom: expression(this.innerHTML = '...'); /* IE7 */
}
.dotting:before { content: '...'; } /* IE8 */
.dotting::before { content: ''; }
:root .dotting { margin-left: 2px; padding-left: 2px; } /* IE9+ */

@-webkit-keyframes dot {
    25% { border-color: transparent; background-color: transparent; }
    50% { border-right-color: transparent; background-color: transparent; }
    75% { border-right-color: transparent; }
}
@keyframes dot {
    25% { border-color: transparent; background-color: transparent; }
    50% { border-right-color: transparent; background-color: transparent; }
    75% { border-right-color: transparent; }
}

打字机效果(纯css)


CSS
<style>
      .typing {
          width: 15em;
          white-space: nowrap;
          border-right: 2px solid transparent;
          animation: typing 3.5s steps(15, end), blink-caret .75s step-end infinite;
          overflow: hidden;
      }
      /* 打印效果 */
      @keyframes typing {
        from { width: 0; }
        to { width: 15em; }
      }
      /* 光标闪啊闪 */
      @keyframes blink-caret {
        from, to { box-shadow: 1px 0 0 0 transparent; }
        50% { box-shadow: 1px 0 0 0; }
      }
    </style>

HTML
<p class="typing">-----------------------------------------</p>

翻页特效

    content: '';
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    height: 40px;
    overflow: hidden;
    -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2), 0 8px 0 -3px #f6f6f6, 0 9px 1px -3px rgba(0, 0, 0, 0.2), 0 16px 0 -6px #f6f6f6, 0 17px 2px -6px rgba(0, 0, 0, 0.2);
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2), 0 8px 0 -3px #f6f6f6, 0 9px 1px -3px rgba(0, 0, 0, 0.2), 0 16px 0 -6px #f6f6f6, 0 17px 2px -6px rgba(0, 0, 0, 0.2);
}

时间戳转化为时间格式字符串

function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + '/';
    let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '/';
    let D = date.getDate() < 10 ? '0'+ date.getDate()+ ' ' : date.getDate()+ ' ';
    let h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
    let m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes()) + ':';
    let s = (date.getSeconds()+1 < 10 ? '0'+(date.getSeconds()+1) : date.getSeconds()+1);
    return Y+M+D+h+m+s;
}

原生js实现删除数组中的某一个元素:

Array.prototype.indexOf = function(val) { 
	for (var i = 0; i < this.length; i++) { 
		if (this[i] == val) return i; 
	} 
	return -1; 
};
Array.prototype.remove = function(val) { 
	var index = this.indexOf(val); 
		if (index > -1) { 
		this.splice(index, 1); 
	} 
}; 

//使用实例
var arr = [1,2,3];
arr.remove(1);

arr = [2,3]

标题字数限制

$('.fourmTitle').on('input propertychange keydown change', function() {  
     var self = this;
    
     setTimeout(function() {
		console.log($(self).val().length);
		console.log($(self).val());
     })
}); 

边框既有圆角又有渐变的的实现

.prosItemBtn div {
    width: 73px;
    height: 24px;
    display: inline-block;
    line-height: 24px;
    text-align: center;
    color: rgb(72, 142, 255);
    margin-right: 13px;
    font-size: 12px;
    padding: 1px;
    border-radius: 5px;
    background: -webkit-linear-gradient(right, rgb(255, 255, 255) 0%, rgb(255, 255, 255) 100%) content-box, -webkit-linear-gradient(top, rgb(27, 205, 253) 0%, rgb(25, 104, 233) 100%) padding-box;
}

格式化金额 保留n位小数(默认2位),不足的补零,整数每3位用都好隔开

function formatMoney(s,n) {  
	n = n > 0 && n <= 20 ? n : 2;  //配置保留几位小数
	s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
	var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
	t = "";
	for (i = 0; i < l.length; i++) {
		t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
	}
	return t.split("").reverse().join("") + "." + r;
} 

将时间对象转换成时间格式的字符串

function formatDateTime(date) { //传入一个时间对象
	Y = date.getFullYear() + '-';
	M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
	D = date.getDate() + ' ';
	h = date.getHours() + ':';
	m = date.getMinutes() + ':';
	s = date.getSeconds(); 
	return Y+M+D+h+m+s;
}

验证码倒计时

其中的参数为:

  1. phoneDom为手机号输入框元素
  2. codeInput为验证码输入框元素
  3. dom为“发送验证码”按钮
  4. count为倒计时时间(秒)
function sendMessage(phoneDom,codeInput,dom,count) {
    if(phoneDom.val() == ""){
        layer.msg("请输入手机号",{icon:0})
    }else if(!(/^1[3|4|5|7|8][0-9]\d{4,8}$/.test(phoneDom.val()))){
        layer.msg("请输入正确的手机号",{icon:0})
    }else{
	   codeInput.attr('disabled',false);
       codeInput.focus();
       var curCount = count;
       $(dom).attr("disabled", "true"); 
       var InterValObj = window.setInterval(function(){
       $(dom).val(curCount + "秒");
       curCount--;
           if (curCount == -1) {  
               clearInterval(InterValObj);
                $(dom).removeAttr("disabled");
                $(dom).val("重新发送"); 
            } 
        }, 1000);
    }
}

//使用实例:
<input type="text" class="phone" placeholder="请输入手机号" >
<input type="text" class="code" placeholder="请输入验证码" disabled>
<input type="button" onclick="sendMessage($('.phone'),$('.code'),this,10)" value="获取验证码"></input>

水平方向上,出现滚定条

overflow-x:auto ;  
overflow-y: hidden;
white-space: nowrap;

文字溢出后,文字省略,显示三个点

overflow: hidden;
white-space:nowrap;
text-overflow: ellipsis;

水平垂直居中

width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
margin: -50px 0 0 -50px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
display: flex;//flex布局
justify-content: center;//使子项目水平居中
align-items: center;//使子项目垂直居中
//html
<div class="parent2">
    <span></span>
     <div class="child">hello world-2</div>
 </div>

//css
.parent2{
    height:300px;
    width: 300px;
    text-align: center; //重要
    background: #FD0C70;
}
.parent2 span{
    display: inline-block;;
    width: 0;
    height: 100%;
    vertical-align: middle;
    zoom: 1;
}
.parent2 .child{
    display: inline-block;
    color: #fff;
    zoom: 1;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值