天给大家分享一些实用的JS代码片段,有需要的朋友欢迎收藏!
1、获取浏览器的版
- function getBrowser() {
- var UserAgent = navigator.userAgent.toLowerCase();
- var browserInfo = {};
- var browserArray = {
- IE: window.ActiveXObject || "ActiveXObject" in window, // IE
- Chrome: UserAgent.indexOf('chrome') > -1 && UserAgent.indexOf('safari') > -1, // Chrome浏览器
- Firefox: UserAgent.indexOf('firefox') > -1, // 火狐浏览器
- Opera: UserAgent.indexOf('opera') > -1, // Opera浏览器
- Safari: UserAgent.indexOf('safari') > -1 && UserAgent.indexOf('chrome') == -1, // safari浏览器
- Edge: UserAgent.indexOf('edge') > -1, // Edge浏览器
- QQBrowser: /qqbrowser/.test(UserAgent), // qq浏览器
- WeixinBrowser: /MicroMessenger/i.test(UserAgent) // 微信浏览器
- };
- // console.log(browserArray)
- for (var i in browserArray) {
- if (browserArray[i]) {
- var versions = '';
- if (i == 'IE') {
- versions = UserAgent.match(/(msie\s|trident.*rv:)([\w.]+)/)[2];
- } else if (i == 'Chrome') {
- for (var mt in navigator.mimeTypes) {
- //检测是否是360浏览器(测试只有pc端的360才起作用)
- if (navigator.mimeTypes[mt]['type'] == 'application/360softmgrplugin') {
- i = '360';
- }
- }
- versions = UserAgent.match(/chrome\/([\d.]+)/)[1];
- } else if (i == 'Firefox') {
- versions = UserAgent.match(/firefox\/([\d.]+)/)[1];
- } else if (i == 'Opera') {
- versions = UserAgent.match(/opera\/([\d.]+)/)[1];
- } else if (i == 'Safari') {
- versions = UserAgent.match(/version\/([\d.]+)/)[1];
- } else if (i == 'Edge') {
- versions = UserAgent.match(/edge\/([\d.]+)/)[1];
- } else if (i == 'QQBrowser') {
- versions = UserAgent.match(/qqbrowser\/([\d.]+)/)[1];
- }
- browserInfo.type = i;
- browserInfo.versions = parseInt(versions);
- }
- }
- return browserInfo;
- }
2、颜色RGB转十六进制
- function colorRGBtoHex(color) {
- var rgb = color.split(',');
- var r = parseInt(rgb[0].split('(')[1]);
- var g = parseInt(rgb[1]);
- var b = parseInt(rgb[2].split(')')[0]);
- var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
- return hex;
- }
3、禁止右键菜单代码、禁止复制粘贴代码
- < script type = "text/javascript" >
- //屏蔽右键菜单
- document.oncontextmenu = function(event) {
- if (window.event) {
- event = window.event;
- }
- try {
- var the = event.srcElement;
- if (! ((the.tagName == "INPUT" && the.type.toLowerCase() == "text") || the.tagName == "TEXTAREA")) {
- return false;
- }
- return true;
- } catch(e) {
- return false;
- }
- }
- //屏蔽粘贴
- document.onpaste = function(event) {
- if (window.event) {
- event = window.event;
- }
- try {
- var the = event.srcElement;
- if (! ((the.tagName == "INPUT" && the.type.toLowerCase() == "text") || the.tagName == "TEXTAREA")) {
- return false;
- }
- return true;
- } catch(e) {
- return false;
- }
- }
- //屏蔽复制
- document.oncopy = function(event) {
- if (window.event) {
- event = window.event;
- }
- try {
- var the = event.srcElement;
- if (! ((the.tagName == "INPUT" && the.type.toLowerCase() == "text") || the.tagName == "TEXTAREA")) {
- return false;
- }
- return true;
- } catch(e) {
- return false;
- }
- }
- //屏蔽剪切
- document.oncut = function(event) {
- if (window.event) {
- event = window.event;
- }
- try {
- var the = event.srcElement;
- if (! ((the.tagName == "INPUT" && the.type.toLowerCase() == "text") || the.tagName == "TEXTAREA")) {
- return false;
- }
- return true;
- } catch(e) {
- return false;
- }
- }
- //屏蔽选中
- document.onselectstart = function(event) {
- if (window.event) {
- event = window.event;
- }
- try {
- var the = event.srcElement;
- if (! ((the.tagName == "INPUT" && the.type.toLowerCase() == "text") || the.tagName == "TEXTAREA")) {
- return false;
- }
- return true;
- } catch(e) {
- return false;
- }
- } < /script>/
4、检查日期是否合法
- function CheckDateTime(str){
- var reg = /^(\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
- var r = str.match(reg);
- if(r==null)return false;
- r[2]=r[2]-1;
- var d= new Date(r[1], r[2],r[3], r[4],r[5], r[6]);
- if(d.getFullYear()!=r[1])return false;
- if(d.getMonth()!=r[2])return false;
- if(d.getDate()!=r[3])return false;
- if(d.getHours()!=r[4])return false;
- if(d.getMinutes()!=r[5])return false;
- if(d.getSeconds()!=r[6])return false;
- return true;
- }
5、英文字符串首字母大写
- /**
- * 方法一:js字符串切割
- * @param {*} str
- */
- function firstToUpper1(str) {
- return str.trim().toLowerCase().replace(str[0], str[0].toUpperCase());
- }
- /**
- * 方法二:js正则
- * @param {*} str
- */
- function firstToUpper2(str){
- return str.replace(/\b(\w)(\w*)/g, function($0, $1, $2) {
- return $1.toUpperCase() + $2.toLowerCase();
- });
- }
- /**
- * 方法三:js正则
- * @param {*} str
- */
- function firstToUpper3(str){
- return str.toLowerCase().replace(/( |^)[a-z]/g,(L)=>L.toUpperCase());
- }
6、计算2个日期之间相差多少天
- function getDays(strDateStart,strDateEnd){
- var strSeparator = "-"; //日期分隔符
- var oDate1;
- var oDate2;
- var iDays;
- oDate1= strDateStart.split(strSeparator);
- oDate2= strDateEnd.split(strSeparator);
- var strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
- var strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
- iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24)//把相差的毫秒数转换为天数
- return iDays ;
- }
7、生成随机十六进制颜色
- function randomHexColor() {
- //随机生成十六进制颜色
- var hex = Math.floor(Math.random() * 16777216).toString(16);
- //生成ffffff以内16进制数
- while (hex.length < 6) {
- //while循环判断hex位数,少于6位前面加0凑够6位 hex = '0' + hex; }
- return '#' + hex; //返回‘#'开头16进制颜色
- }
8、数组去重
- const removeDuplicates = (arr) => [...new Set(arr)];
- console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6]));
- // Result: [ 1, 2, 3, 4, 5, 6 ]
9、从 URL 获取查询参数
- function getParameterByName(name, url) {
- if (!url) url = window.location.href;
- name = name.replace(/[\[\]]/g, "\\$&");
- var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
- results = regex.exec(url);
- if (!results) return null;
- if (!results[2]) return '';
- return decodeURIComponent(results[2].replace(/\+/g, " "));
- }
10、校验数字是奇数还是偶数
- const isEven = num => num % 2 === 0;
- console.log(isEven(2));
- // Result: True
11、求数字的平均值
- const average = (...args) => args.reduce((a, b) => a + b) / args.length;
- average(1, 2, 3, 4);
- // Result: 2.5
12、回到顶部
- function topFunction() {
- document.body.scrollTop = 0;
- document.documentElement.scrollTop = 0;
- }
13、翻转字符串
- // reverse
- var name = "My city is WH";
- var resultStr = name.split('').reverse().join('');
- console.log(resultStr); // HW si ytic yM// charAt
- var name = "My city is WuHan";
- var nameArr = name.split('');
- var resultStr = '';
- for (var i = nameArr.length-1; i >= 0; i--) {
- resultStr += name.charAt(i);
- }
- console.log(resultStr); // naHuW si ytic yM
14、校验数组是否为空
- const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
- isNotEmpty([1, 2, 3]);
- // Result: true