实用技巧(2)

2023-11-11 14:33:30发布
90

1、把111122223333转成1111 2222 3333

function cutStringFor4(str) {
    return str.replace(/s/g, '').replace(/(.{4})/g, "$1 ")
}
console.log(cutStringFor4('11112222333344445555'))


2、兼容pc端的背景音乐播放代码

<div id='musiclsit'></div>
 
<script>
    
    function addMusic(path, list)
    {
        if(window.addEventListener)
        { 
            var str = '<audio src='+ path +' hidden="true" autoplay="true" loop="true"></audio>';
            document.getElementById(list).innerHTML = str;
        }
        else if(window.attachEvent)
        { 
           var str = '<embed src='+ path +' autostart="true" loop="true" hidden="true"></embed>';
           document.getElementById(list).innerHTML = str;
        }
    }
 
    addMusic('swf/bgm.mp3', 'musiclsit');
 
</script>


3、格式化json

function getStr(json){
  //删除空字段
  Object.keys(json).forEach(key => {
    !json[key] && delete json[key];
  });
  //拼接成xxx&xxx的格式,用于get请求
  let queryStr = Object.keys(json)
    .map(key => {
      return `${key}=${json[key]}`;
    }).join("&");
 
  return queryStr;
}
 
console.log(getStr({
	name : 'tom',
	age : 18,
	tall : null,
	money : ''
}));
 
//输出name=tom&age=18


4、产生不重复的随机数

/*
	count : 随机数的个数
	numericalRange : 随机数范围
*/
function NonRepeatedRandomVal( count, numericalRange )
{
	var array = [];
	var i = 0;
	var tempArray = numericalRange.split('~');
	var x1 = parseInt( tempArray[0] );
	var x2 = parseInt( tempArray[1] );
 
	if (x2 - x1 < count) {
		alert('产生的随机数个数不能小于最大范围!');
		return false;
	}
	
	while(i < count)
	{
		var flag = true;
 
		var temp = parseInt( x1 + Math.random() * (x2 - x1) );
 
		for(var i=0; i<array.length; i++)
		{
			if (array[i] == temp) 
			{
				flag = false;
				break;
			}
		}
 
		if (flag) 
		{
			array.push(temp);
			i++;
		}
	}
 
	return array;
}
 
//测试例子
var array = NonRepeatedRandomVal( 100, '0~100' );
if (array) 
{
	console.log( array.sort(function(a, b){
		return a - b;
	}) );
}


5、深拷贝

function deepClone(initalObj, finalObj) {
    let obj = finalObj || {};
    for (let i in initalObj) {
        let prop = initalObj[i];        // 避免相互引用对象导致死循环,如initalObj.a = initalObj的情况
        if (prop === obj) {
            continue;
        }
        if (typeof prop === 'object') {
            obj[i] = (prop.constructor === Array) ? [] : {};
            arguments.callee(prop, obj[i]);
        } else {
            obj[i] = prop;
        }
    }
    return obj;
}
 
// 被拷贝的对象
const obj = { 
    msg: { 
        name: "tom", 
        age: 21 
    } 
};
 
// 把obj 和 {tel : '15812520368'} 都拷贝到obj1上
let obj1 = deepClone(obj,{tel : '15812520368'});
console.log(obj1);
 
// 把obj1拷贝到obj2上
let obj2 = deepClone(obj);
console.log(obj2);


6、快速删除指定元素

var arr = [1, 2, 3, 4, 5];
arr = arr.filter(function (num) {
    return num != 5; // 数组中的每个元素都会遍历,如果值不等于5,则返回true,该值会保留。否则返回false,该值不被保留
});
console.log(arr);


7、打字机效果

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>打字机效果</title>
</head>
 
<body>
    <div id="content"></div>
    <script>
        function typeWriter(config) {
            let index = 0;
            const id = setInterval(() => {
                const s = config.data.text.substr(0, index);
                config.el.innerHTML = `${s} |`;
                index++;
                if (s.length >= config.data.text.length) {
                    clearInterval(id);
                    config.el.innerHTML = config.el.innerHTML.substr(0, config.el.innerHTML.length - 1);
                }
            }, config.data.speed || 100);
        }
 
        typeWriter({
            el: document.getElementById('content'),
            data: {
                text: 'JavaScript一种直译式脚本语言,是一种动态类型、弱类型、基于原型的语言,内置支持类型。它的解释器被称为JavaScript引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在HTML(标准通用标记语言下的一个应用)网页上使用,用来给HTML网页增加动态功能。在1995年时,由Netscape公司的BrendanEich,在网景导航者浏览器上首次设计实现而成。因为Netscape与Sun合作,Netscape管理层希望它外观看起来像Java,因此取名为JavaScript。但实际上它的语法风格与Self及Scheme较为接近。为了取得技术优势,微软推出了JScript,CEnvi推出ScriptEase,与JavaScript同样可在浏览器上运行。为了统一规格,因为JavaScript兼容于ECMA标准,因此也称为ECMAScript。',
                speed: 50
            }
        });
    </script>
</body>
 
</html>


8、jquery实现的select组件

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        ul {
            list-style-type: none;
        }

        .option-body {
            display: inline-block;
            position: relative;
            margin: 100px;
            font-size: 14px;
            color: #333;
            cursor: pointer;
        }

        .option-ctx {
            background: #fff;
            border-radius: 4px;
            filter: drop-shadow(0 0 2px #ccc);
            display: inline-block;
            position: absolute;
            top: 35px;
            left: 0;
            transition: 0.2s ease;
            height: 0;
            overflow: hidden;
        }

        .option-ctx::after {
            position: absolute;
            content: '';
            width: 0;
            height: 0;
            border-top: 8px solid transparent;
            border-left: 8px solid transparent;
            border-right: 8px solid transparent;
            border-bottom: 8px solid #fff;
            top: -16px;
            left: 30px;
        }

        .option {
            padding: 5px;
            cursor: pointer;
        }

        .on,
        .option:hover {
            color: #0071dc;
            background: #e5f1fc;
        }

        .option-body .now {
            display: flex;
            align-items: center;
        }

        .option-body .now::after {
            content: '';
            width: 6px;
            height: 6px;
            border-right: 1px solid #000;
            border-bottom: 1px solid #000;
            display: inline-block;
            transform: rotate(45deg);
            margin-left: 10px;
            transition: 0.2s ease;
            transform-origin: 50% 50%;
        }

        .option-body .up::after {
            transform: rotate(225deg) translateY(-3px);
            ;
        }
    </style>
</head>

<body>
    <div class="option-ctx" bindClass="myoption">
        <div class="option" value="1">综合排序</div>
        <div class="option" value="2">价格高序</div>
        <div class="option" value="3">价格低序</div>
        <div class="option" value="4">新品</div>
    </div>
    <div class="option-ctx">
        <div class="option" value="1">12</div>
        <div class="option" value="2">24</div>
        <div class="option" value="3">48</div>
    </div>
    <script src="./jquery.min.js"></script>
    <script>
        (function () {
            var optionList = $('.option-ctx');
            for (var i = 0; i < optionList.length; i++) {
                var o = optionList[i];
                $(o).find('.option').eq(0).addClass('on'); // 第一个option设置选中
                $(o).wrap("<div class='option-body'></div>"); // option-ctx的外部包裹一个div
                $(o).closest('.option-body').addClass($(o).attr('bindClass')); // 自定义类名
                $(o).closest('.option-body').append(`<span class='now'>${$(o).find('.option').eq(0).html()}</span>`); // 目前选中的select
                $(o).css('width', parseInt($(o).closest('.option-body').css('width')) + 14 + 'px'); // 设置option-ctx的宽度
            }

            // 点击事件
            $('body').on('click', '.option-body', function () {
                var optionCtx = $(this).find('.option-ctx');
                if (parseInt(optionCtx.css('height')) == 0) {
                    $(this).closest('.option-body').find('.now').addClass('up');
                    optionCtx.css({
                        'height': optionCtx.children().length * 29 + 'px'
                    }).addClass('show');
                } else {
                    $(this).closest('.option-body').find('.now').removeClass('up');
                    optionCtx.css({
                        'height': '0'
                    }).removeClass('show');
                }
            });

            $('.option-body .option').on('click', function () {
                $(this).parent().find('.option').removeClass('on');
                $(this).addClass('on');
                $(this).closest('.option-body').find('.now').html($(this).html());
            });
        }());


        $('.myoption .option').on('click', function () {
            alert($(this).attr('value'))
        });
    </script>
</body>

</html>



9、搜索高亮(支持分词搜索)

highTxt: function (n) {
        var sKey = UTILS_MODEL.getQueryString('key').trim();
        var red_reg = new RegExp( sKey.replace(/[(),./-$*|+?{}:=!]/g, '$&').replace(/s+/g,'|') ,"ig");
        return (n + '').replace(red_reg,"<span class='Highlight'>$&</span>");
    },


10、a标签嵌套a标签

使用object标签进行嵌套,作为子元素的a标签放在object标签里面,这样浏览器解析的与HTML里面编辑的是一样的。

<a href="###">
	<div class="index-lb1">
		<img src="img/index-lb1.jpg" alt="">
			<object><a class="banner_view" href="###">VIEW</a></object>
	</div>
</a>


11、解决ios,input输入框获得焦点时,页面会放大的bug

解决方法1,添加以下meta

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

解决方法2,input的font-size设置必须大于等于16px


12、快速获得日期格式化(兼容性不太好,需要用babel转成es5)

var d = new Date();
console.log(d.toLocaleString()); // 输出 :2024/6/15 12:22:57


13、字体两边对齐(text-align-last: justify;)

 <div class="item">
     <span class="label">姓名</span>:
     <span class="value">呵呵</span>
</div>
<div class="item">
     <span class="label">出生日期</span>:
     <span class="value">25他</span>
</div>
 
 
<style>
 
.item {
    margin-bottom: 8px;
    .label {
      display: inline-block;
      height: 100%;
      width: 100px;
      text-align: justify;
      text-align-last: justify;
    }
    .value {
      padding-right: 10px;
    }
  }
</style>


14、文本复制

export const setClipboardData = (value: string) => {
  const textarea = document.createElement('textarea');
  textarea.setAttribute('readonly', 'readonly');
  textarea.value = value;
  document.body.appendChild(textarea);
  textarea.select();
  if (document.execCommand('copy')) {
    document.execCommand('copy');
  }
  document.body.removeChild(textarea);
}


15、解决移动端,返回上一页,页面不刷新的问题

window.onpageshow = function(event) {
    if(event.persisted || (window.performance && window.performance.navigation.type == 2)) {
        window.location.reload()
    }
};


16、两位小数相加,解决精度问题(只适用于2位小数)

for (let i = 0; i < 10000; i++) {
    const a = Number( Math.random().toFixed(2) ) * 1000;
    const b = Number( Math.random().toFixed(2) ) * 1000;
    const sum = (a + b) / 1000;
    console.log(`${a / 1000} + ${b / 1000} = ${sum}`);

}