前端开发中一些小知识点(更新中)

1. 无法选中文字css方法

user-select:none | tex t| all | element (IE9以上支持)

  • none: 文本不能被选择
  • text: 可以选择文本
  • all : 当所有内容作为一个整体时可以被选择。如果双击或者在上下文上点击子元素,那么被选择的部分将是以该子元素向上回溯的最高祖先元素。
  • element: 可以选择文本,但选择范围受元素边界的约束
.no-select{
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none; /* Chrome/Safari/Opera */
  -khtml-user-select: none; /* Konqueror */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* Internet Explorer/Edge */
  user-select: none; /* Non-prefixed version, currently not supported by any browser */
}

2. 文字单行显示,超出显示省略号

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

3. 文字n行显示,超出显示省略号

{
	overflow-y: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    /* 这里的n为显示行数 */
    -webkit-line-clamp:n;
    -webkit-box-orient: vertical;
}

4. 元素隐藏但仍占有位置

{
  visibility: hidden;
}

5. Vue路由跳转后回到视图顶部

mounted() {
	this.$router.afterEach((to, from, next) => {
		window.scrollTo(0, 0)
	})
},

6. 背景渐变

线性渐变: linear-gradient(to bottom,colorStrat,colorEnd
放射渐变: radial-gradient(circle at center top,colorStrat,colorEnd)

7. 复制文本到粘贴板

export const copyText = (T) => {
  if (!T) return '';
  let copyDom = document.createElement('input');
  copyDom.setAttribute('value', T);
  document.body.appendChild(copyDom);
  copyDom.select();
  let res = document.execCommand('copy');
  document.body.removeChild(copyDom);
  return res;
}

8. 长按复制(vue)

  <div class="img-box">
    <img v-lazy="require('@/assets/images/QR.png')"
         alt=""
         @touchstart="star($event)"
         @touchend="end()">
  </div>
  methods: {
    star (event) {
      if (!this.isWeChat) {
        event.preventDefault()
        timeOutEvent = setTimeout(() => {
          this.longPressCopy()
        }, 1000);
      }
    },
    end () {
      if (!this.isWeChat) {
        clearTimeout(timeOutEvent)
        timeOutEvent = null
      }
    },
    // 长按复制
    longPressCopy () {
      copyText(this.wechatAccount)
      this.$toast("复制成功,您可以打开微信添加好友")
    },
  },

9. 判断微信内置浏览器

// 判断是否是微信内置浏览器
is_wechat () {
  var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    return true;
  } else {
    return false;
  }
}

10. 时间戳格式化

filters: {
    formatDate: function (value) {
      // 时间戳转换日期格式方法
      if (value == null) {
        return "";
      } else {
        let date = new Date(value);
        let y = date.getFullYear(); // 年
        let MM = date.getMonth() + 1; // 月
        MM = MM < 10 ? "0" + MM : MM;
        let d = date.getDate(); // 日
        d = d < 10 ? "0" + d : d;
        let h = date.getHours(); // 时
        h = h < 10 ? "0" + h : h;
        let m = date.getMinutes(); // 分
        m = m < 10 ? "0" + m : m;
        let s = date.getSeconds(); // 秒
        s = s < 10 ? "0" + s : s;
        return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
      }
    }
  },
Vue.prototype.$formatDate = (value, type = 0, symbol1 = "-", symbol2 = ":", symbol3 = " ") => {
  // type 1 年月日
  // type 2 年月
  let time = value;
  if (!time) {
    return "时间格式错误"
  }
  if (isNaN(value)) {
    time = String(time).replace(/-/g, "/")
  } else {
    if (String(time).length == 10) {
      time = time * 1000;
    }
  }
  let date = new Date(time);
  let y = date.getFullYear(); // 年
  let MM = date.getMonth() + 1; // 月
  MM = MM < 10 ? "0" + MM : MM;
  let d = date.getDate(); // 日
  d = d < 10 ? "0" + d : d;
  let h = date.getHours(); // 时
  h = h < 10 ? "0" + h : h;
  let m = date.getMinutes(); // 分
  m = m < 10 ? "0" + m : m;
  let s = date.getSeconds(); // 秒
  s = s < 10 ? "0" + s : s;
  if (type == 1) {
    return y + symbol1 + MM + symbol1 + d;
  } else if (type == 2) {
    return y + symbol1 + MM;
  }
  return y + symbol1 + MM + symbol1 + d + symbol3 + h + symbol2 + m + symbol2 + s;
}

11. flex中防止元素被挤压变形

{
	flex-shrink: 0;
}

12. 判断手机系统类型

vue中要在$nextTick()中执行

var u = navigator.userAgent,
isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1,
isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
if (isAndroid) {
	console.log('isAndroid')
} else if (isIOS) {
	console.log('isiOS')
}

13. ‘/n’换行不生效

 style="white-space: pre-wrap;"

14. 中英文混用文本尾部不对齐

 style="text-align: justify;"

15. 关于正则表达式

// 手机号验证
/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
// 邮箱
/^[A-Za-zd0-9]+([-_.][A-Za-zd]+)*@([A-Za-z\d]+[-.])+[A-Za-zd]{2,5}$/

16. 首字母排序分组

安装第三方插件:npm i --save js-pinyin
export const sortByFirstLetter = function (origin: any[], target: string = 'name') {
  origin = origin.sort((pre: any, next: any) =>
    Pinyin.getFullChars(pre[target]).localeCompare(Pinyin.getFullChars(next[target]))
  );
  const newArr: any[] = [];
  var letters = "ABCDEFGHIJKLNMOPQRSTUVWXYZ#".split('');
  origin.map((item: any) => {
    // 取首字母
    let key = Pinyin.getFullChars(item[target]).charAt(0).toUpperCase();
    if (!letters.includes(key)) {
      key = '#';
    }
    const index = newArr.findIndex((subItem) => subItem.key === key);
    if (index < 0) {
      newArr.push({
        key: key,
        list: [item]
      });
    } else {
      newArr[index].list.push(item);
    }
  });
  if (newArr[0].key === '#') {
    newArr.push(newArr[0]);
    newArr.splice(0, 1);
  }
  return newArr;
}

17. 图片资源加载错误处理

	document.addEventListener(
      "error",
      (e) => {
        let target = e.target;
        const tagName = target.tagName || "";
        let type = tagName.toLowerCase();
        console.log(tagName.toLowerCase());
        if (tagName.toLowerCase() === "img" && !target.flag) {
          target.flag = true;
          target.src = target.src.replace("format,webp", "format,jpg");
        }
        target = null;
      },
      true
    );

18. IOS时间戳获取NaN问题

时间格式里的-需要替换为/

let time = '2022-11-11'.replace(/-/g, "/");
let date = Date.parse(`${time} 23:59:59`);

19. 金额三位分节显示方式

toLocaleString的兼容性不好

money.toLocaleString();

可更换为

// 不兼容小数
	filtermoney(money, decimal, symbol) {
      if (!money || isNaN(money)) return "0";
      var num = parseFloat(money);
      num = String(num.toFixed(decimal ? decimal : 0));
      var re = /(-?\d+)(\d{3})/;
      while (re.test(num)) {
        num = num.replace(re, "$1,$2");
      }
      return symbol ? symbol + num : num;
    },
// 兼容小数,小数部分不分节
if (!money || isNaN(money)) return "0";
      return money.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");

20. 判断安卓、苹果手机

  var u = navigator.userAgent,
    isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1,
    isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  if (isAndroid) {
    this.phoneOs = 2;
  } else if (isiOS) {
    this.phoneOs = 3;
  }

21. 当天零点时间戳获取

new Date(new Date().toLocaleDateString()).getTime();

22. 浮点数运算精度问题

Number.EPSILON实际上是 JavaScript 能够表示的最小精度。

Math.round((num + Number.EPSILON) * 100) / 100

23. 模拟透明图方格背景

.bg {
	background-image:
		repeating-linear-gradient( #eee 0 8px, transparent 0 16px ),
		repeating-linear-gradient(90deg, #eee 0 8px, transparent 0 16px);
	background-blend-mode: screen;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值