JS常用方法
原创
©著作权归作者所有:来自51CTO博客作者情绪零碎o的原创作品,请联系作者获取转载授权,否则将追究法律责任
JS常用方法
整数随机数函数
//生成从minNum到maxNum的随机数
function randomNum(minNum, maxNum) {
switch (arguments.length) {
case 1:
return parseInt(Math.random() * minNum + 1, 10);
break;
case 2:
return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
break;
default:
return 0;
break;
}
}
监听长按事件PC
// PC长按
$(".xx").touched(function () {
timeout = setTimeout(function () {
console.log('长按事件触发')
}, 1000);//鼠标按下1秒后发生alert事件
});
$(".xx").mouseup(function () {
clearTimeout(timeout);//清理掉定时器
});
$(".xx").mouseout(function () {
clearTimeout(timeout);//清理掉定时器
});
监听长按事件移动端
$(".wx span").on({
touchstart: function() {
timeout = setTimeout(function () {
$('.gowx').click()
}, 1000);//鼠标按下1秒后发生alert事件
},
touchmove: function() {
clearTimeout(timeout);//清理掉定时器
},
touchend: function() {
clearTimeout(timeout);//清理掉定时器
}
})
复制到剪切板
// 复制到剪切板
function copyTXT() {
// 获取需要复制的文字
const copyStr = wxArr[index]
// 创建input标签存放需要复制的文字
const oInput = document.createElement('input');
// 把文字放进input中,供复制
oInput.value = copyStr;
document.body.appendChild(oInput);
// 选中创建的input
oInput.select();
// 执行复制方法, 该方法返回bool类型的结果,告诉我们是否复制成功
const copyResult = document.execCommand('copy')
// 操作中完成后 从Dom中删除创建的input
document.body.removeChild(oInput)
}
数字保留一位小数
// 保留1位小数
function fomatFloat(value, n) {
var f = Math.round(value * Math.pow(10, n)) / Math.pow(10, n);
var s = f.toString();
var rs = s.indexOf('.');
if (rs < 0) {
s += '.';
}
for (var i = s.length - s.indexOf('.'); i <= n; i++) {
s += "0";
}
return s;
},
声明数组
const array = Array(5).fill('');
// 输出
(5) ["", "", "", "", ""]
返回当前时间格式化
function getDateTime() {
var date = new Date(),
year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate(),
hour = date.getHours() + 1,
minute = date.getMinutes(),
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i <10) {
i = “0” + i;
}
return i;
}
return “” + year + “year” + month + “month” + day + “day” + hour + “hour” + minute + “minute” + second + “second”
}