一些 JavaScript JS 函数

数组过滤重复值

//数组过滤重复值
function uniqueArr(array) {
  var n = []; //结果数组
  //从第一项开始遍历
  for (var i = 0; i < array.length; i++) {
	//如果当前数组的第i项在当前数组中第一次出现的位置不是i,
	//那么表示第i项是重复的,忽略掉。否则存入结果数组
	if (array.indexOf(array[i]) == i) n.push(array[i]);
  }
  return n;
}

删除空字符换行,过滤表格 text 中多余的空格

function Trim(str,is_global){
  var result;
  result = str.replace(/(^\s+)|(\s+$)/g,"");
  if(is_global && is_global.toLowerCase()=="g"){
	result = result.replace(/\s/g,"");
  }
  return result;
}

JS 中空的判断

alert(0 == ''); //true
alert(0 == false); //true
alert(false == ''); //true
alert(null == undefined); //true

alert(!0); //true
alert(!false); //true
alert(!undefined); //true
alert(!null); //true
alert(!''); //true

alert(0 == undefined); //false
alert(0 == null); //false
alert(false == null); //false
alert(false == undefined);//false
alert('' == null); //false
alert('' == undefined); //false

typeof(undefined) == 'undefined'
typeof(null) == 'object'
typeof("") == 'string'
typeof(0) == 'number'
typeof(false) == 'boolean'

String(undefined) -> "undefined"
String(null) -> "null"
String("") -> ""
String(0) -> "0"
String(false) -> "false"

区分 JS 中的 undefined , null , “” , 0 和 false

https://www.cnblogs.com/yangzhx/p/4019073.html

JS 移除 数组中指定元素

//首先需要找到元素的下标:
var array = [2, 5, 9];
var index = array.indexOf(5);
//使用splice函数进行移除:
if (index > -1) {
    array.splice(index, 1);
}
//splice函数的第二个参数指删除的数目。splice直接修改原数组,并把删除的所有元素以另一个新数组的方式返回。

数字前补零

function PrefixInteger(num, length) {
  return (Array(length).join('0') + num).slice(-length);
}

Toast 弹窗

function Toast(msg,duration){
  duration=isNaN(duration)?3000:duration;
  var m = document.createElement('div');
  m.innerHTML = msg;
  m.style.cssText="width: 60%;min-width: 150px;opacity: 0.7;height: 30px;color: rgb(255, 255, 255);line-height: 30px;text-align: center;border-radius: 5px;position: fixed;top: 40%;left: 20%;z-index: 999999;background: rgb(0, 0, 0);font-size: 12px;";
  document.body.appendChild(m);
  setTimeout(function() {
    var d = 0.5;
    m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
    m.style.opacity = '0';
    setTimeout(function() { document.body.removeChild(m) }, d * 1000);
  }, duration);
}

复制文本

//复制文本
function copy (id, attr='innerHTML') {
  let target = null;
  if (attr) {
    target = document.createElement('div');
    target.id = 'tempTarget';
    target.style.opacity = '0';
    if (id) {
      let curNode = document.querySelector('#' + id);
      target.innerText = curNode[attr];
    } else {
      target.innerText = attr;
    }
    document.body.appendChild(target);
  } else {
    target = document.querySelector('#' + id);
  }
  try {
    let range = document.createRange();
    range.selectNode(target);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    console.log('复制成功:' + range)
  } catch (e) {
    console.log('复制失败')
  }
  if (attr) {
    // remove temp target
    target.parentElement.removeChild(target);
  }
}

获得链接地址的参数

function getQueryString(name,link=''){
  console.log(link)
  var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
  if(link){
    var num=link.indexOf("?");
    link=link.substr(num+1);
    var r = link.match(reg);
  }else{
    var r = window.location.search.substr(1).match(reg);
  }
  if(r!=null)return  unescape(r[2]); return null;
}

HTML 标签获取 图片地址

img_src: function (str){
  var imgReg = /<img.*?(?:>|\/>)/gi;
  var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
  var arr = str.match(imgReg);    
  var list = []
  for(var i = 0; i < arr.length; i++) {
    var src = arr[i].match(srcReg);
    //获取图片地址
    if (src[1]) {
    list.push(src[1])
    }
    //当然你也可以替换src属性
    if (src[0]) {
      var t = src[0].replace(/src/i, "href");
    }
  }
  console.log(list)
  return list;
},

截取文件后缀

file_ext:function (name){
  let fileName = name.lastIndexOf(".");//取到文件名开始到最后一个点的长度
  let fileNameLength = name.length;//取到文件名长度
  let fileFormat = name.substring(fileName + 1, fileNameLength);//截
  console.log(fileFormat);
  return fileFormat
},

不刷新页面修改地址栏

var stateObject = {};
var title = "修改地址";
var newUrl = '/view/fontface4.html';
//修改地址栏中的地址,后退时返回当前页
history.pushState(stateObject, title, newUrl);
//修改地址栏中的地址,后退时返回前一页
history.replaceState(stateObject, title, newUrl);

jQuery Post 跳转

$.extend({
  StandardPost:function(url,args){
    console.log(args)
    var body = $(document.body),
      form = $("<form method='post'></form>"),
      input;
    form.attr({"action":url});
    $.each(args,function(key,value){
      input = $("<input type='hidden'>");
      input.attr({"name":key});
      input.val(value);
      form.append(input);
    });

    form.appendTo(document.body);
    form.submit();
    document.body.removeChild(form[0]);
  }
});
//使用
$.StandardPost(url,{data:'test'});

jQuery 模拟长按

$("#id").on({
  touchstart: function(e) {
    // 长按事件触发
    timeOutEvent = setTimeout(function() {
      timeOutEvent = 0;
      console.log("长按事件")
    }, 1000);
  },
  touchmove: function() {
    clearTimeout(timeOutEvent);
    timeOutEvent = 0;
  },
  touchend: function() {
    clearTimeout(timeOutEvent);
    timeOutEvent = 0;
    return false;
  }
})

指定日期的上个月,下个月

//下个月
const getNextMonth = function(date) {
  var arr = date.split('-');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var day = arr[2]; //获取当前日期的日
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中的月的天数
  var year2 = year;
  var month2 = parseInt(month) + 1;
  if (month2 == 13) {
    year2 = parseInt(year2) + 1;
    month2 = 1;
  }
  var day2 = day;
  var days2 = new Date(year2, month2, 0);
  days2 = days2.getDate();
  if (day2 > days2) {
    day2 = days2;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }

  var t2 = year2 + '-' + month2 + '-' + day2;
  return t2;
}
//上个月
const getPreMonth = function (date) {
  var arr = date.split('-');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var day = arr[2]; //获取当前日期的日
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中月的天数
  var year2 = year;
  var month2 = parseInt(month) - 1;
  if (month2 == 0) {
    year2 = parseInt(year2) - 1;
    month2 = 12;
  }
  var day2 = day;
  var days2 = new Date(year2, month2, 0);
  days2 = days2.getDate();
  if (day2 > days2) {
    day2 = days2;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }
  var t2 = year2 + '-' + month2 + '-' + day2;
  return t2;
}

HTML 锚点跳转平滑动画

    $('a[href*=#],area[href*=#]').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({
                        scrollTop: targetOffset
                    },
                    200);
                return false;
            }
        }
    });

fSelect.js select 下拉多选框 checkbox 的使用方法

<!DOCTYPE html>
<html>
<head>
	<link href="jquery.fSelect.css" rel="stylesheet" type="text/css" />
	<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
	<script src="jquery.fSelect.js"></script>
	<script>
		$(function() {
			$('.demo').fSelect();
		});
	</script>
</head>
<select class="demo" multiple="multiple">  
    <optgroup label="Languages">  
        <option value="cp">C++</option>  
        <option value="cs">C#</option>  
        <option value="oc">Object C</option>  
        <option value="c">C</option>  
    </optgroup>  
    <optgroup label="Scripts">  
        <option value="js">JavaScript</option>  
        <option value="php">PHP</option>  
        <option value="asp">ASP</option>  
        <option value="jsp">JSP</option>  
    </optgroup>  
</select>
</html>

JS 两个数组合并

//concat()把两个或者多个数组链接在一起,但是不改变已经存在的数组
//而是返回一个链接之后的新数组
var a = [1,2,3];
a.concat([4,5]);
console.log(a);
//此处输出为 [1, 2, 3]

var a = [1,2,3];
a = a.concat([4,5]);
console.log(a);
//此处输出为 [1, 2, 3 ,4 ,5]

Web 生成图片 html2canvas 示例

http://blog.liuguofeng.com/wp-content/uploads/2018/09/html2canvas.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Using an existing canvas to draw on</title>
    <style>	
        button {
            clear: both;
            display: block;
        }
    </style>
</head>
<body>
<div><h1>这是HTML</h1>
	
    <div id="content" style="width:200px;height:200px;background: rgba(100, 255, 255, 0.5);">
	<img src='timg.jpg' style="width:100px;height:60px;">
	<span>这是文字</span>
	</div>
</div>
<h1>生成的图片</h1>
<canvas width="200" height="200"></canvas>
<script type="text/javascript" src="html2canvas.js"></script>
<button>点击生成图片</button>
<script type="text/javascript">
    var canvas = document.querySelector("canvas");
    document.querySelector("button").addEventListener("click", function() {
        html2canvas(document.querySelector("#content"), {canvas: canvas}).then(function(canvas) {
            console.log('Drew on the existing canvas');
        });
    }, false);
</script>
</body>
</html>

JavaScript 实现 Toast 吐司效果

JS

<script>
function Toast(msg,duration){
    duration=isNaN(duration)?3000:duration;
    var m = document.createElement('div');
    m.innerHTML = msg;
    m.style.cssText="width: 60%;min-width: 150px;opacity: 0.7;height: 30px;color: rgb(255, 255, 255);line-height: 30px;text-align: center;border-radius: 5px;position: fixed;top: 40%;left: 20%;z-index: 999999;background: rgb(0, 0, 0);font-size: 12px;";
    document.body.appendChild(m);
    setTimeout(function() {
        var d = 0.5;
        m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
        m.style.opacity = '0';
        setTimeout(function() { document.body.removeChild(m) }, d * 1000);
    }, duration);
}
</script>

HTML

<html>
	<head>
	<style>
	body {
		font-family: 'Lucida Grande', 'Helvetica', sans-serif;
	}
	</style>
	</head>
	<body>
	<button onclick="Toast('这是一个吐司',2000);">Toast</button>
	</body>
</html>

JavaScript POST提交数据并跳转

jQuery

    $.extend({
        StandardPost:function(url,args){
            console.log(args)
            var body = $(document.body),
                form = $("<form method='post'></form>"),
                input;
            form.attr({"action":url});
            $.each(args,function(key,value){
                input = $("<input type='hidden'>");
                input.attr({"name":key});
                input.val(value);
                form.append(input);
            });

            form.appendTo(document.body);
            form.submit();
            document.body.removeChild(form[0]);
        }
    });

via: https://segmentfault.com/q/1010000000473230

IE6/7/8 360浏览器兼容模式 无法正常加载JS 但打开调试模式可以正常加载

遇到个神奇的 BUG,在写前端时,JS 的点击事件在 Chrome 可以正常加载,但到了 IE 或是其他双核浏览器的兼容模式就无法点击,准备调试按了 F12 又莫名的可以点击了,这个问题找了好久。最后清除了缓存出现了提示,”console 未定义”。

IE 浏览器本身未定义 console 对象

解决方法就是删掉 console.log(),或是重新定一下 console.log()