产生在m、n之间的随机整数
//Math.round()把数四舍五入为最接近的整数。
function random(m, n) {
return Math.round(Math.random() * (n - m)) + m;
}
console.log(random(20,30)) //20--30之间整数
将一个dom元素划分成多个小块生成一个数组
//arrayObject.splice(位置,项目数量,新项目)
//返回值:array(新数组)
//ele.offsetHeight返回元素的高
function(ele,n){ //ele:Dom节点 n:分为多少块
var num = new Array()
for (var i = 0; i < ele.offsetHeight / n - 1; i++) num.splice(i, 0, i);
return num
}
//$("barrage")元素的高是400 //分成20个小块
console.log(block($("barrage"),20))//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
定义一个id选择函数
function $(id) {
return document.getElementById(id);
}
//console.log($("barrage")) //获取id是barrage的dom元素
//其它分装需要自己去探索
二分算法
var arr = [1,2,3,4,5,6,7,8]
function helfSearch(ary,num){
var len = ary.length,
middle = Math.floor(len/2),
mNum = ary[middle];
if(len === 0) return null
else if(mNum === num) return middle;
else if(mNum > num) return helfSearch(ary.slice(0,middle),num);
else return helfSearch(ary.slice(middle+1),num);
}
//查找某个元素在数组中的位置
console.log('我是二分算法')
console.log(helfSearch(arr,1));
判断横竖屏
/**
* 判断横竖屏
* 横屏 return 0
* 竖屏 return 1
*/
export let screen = () => {
let WB = document.documentElement.clientWidth,
HB = document.documentElement.clientHeight;
if (WB > HB) return 0;
else return 1;
}
js提交复选框函数
//提交复选框中的数据
function getCheckboxVal(ele) {
//获取所有的复选框[ele:所有复选框的css选择器]
let check_ele = document.querySelectorAll(ele);
let check_val = []; //存放复选框val的数组
for (let k in check_ele) {
//筛选出选中复选框的元素,向check_val中push val值
if (check_ele[k].checked) check_val.push(check_ele[k].value);
}
return check_val
}
console.log(getCheckboxVal(.imgbox input[type=checkbox]))
数组中每一项变为number类型
var arr = ["125","445","22","45","68","32","98"];
//使用map方法,也可以使用for循环
arr = arr.map(function(el){return parseInt(el);}); //[125,445,22,45,68,32,98]
数组合并去重排序
let arr1 = [1, 25, 2, 26, 1234, 6, 213];
let arr2 = [2, 6, 2134, 6, 31, 623];
let c = [...new Set([...arr1, ...arr2])].sort((a, b) => {
return a - b;
});
原生操作class
//判断有无
function hasClass(ele, cls) {
return ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}
//添加
function addClass(ele, cls) {
if (!this.hasClass(ele, cls)) ele.className += " " + cls;
}
//删除
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
let reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
ele.className = ele.className.replace(reg, " ");
}
}
根据离开页面来改变网页title
(function() {
var OriginTitile = document.title, titleTime;
document.addEventListener('visibilitychange', function() {
if (document.hidden) {
document.title = '死鬼去哪里了!';
clearTimeout(titleTime);
} else {
document.title = '(つェ⊂)咦!又好了!';
titleTime = setTimeout(function() {
document.title = OriginTitile;
},2000);
}
});
})();