跳至主要內容

snippet

chanchaw大约 7 分钟javascript

样式

浮动卡片

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>使用box-shadow做出卡片效果</title> 
<style>
div.card {
  width: 300px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);//设置两层阴影
  text-align: center;
	border-radius: 5px;
	padding: 10px;
}
</style>
</head>
<body>
 
<div class="card">
	昭和精工有8个制造基地。在国内拥有数十家加工企业,与国内30多家、海外10多家客户保持合作关系,业务规模不断扩大。
我们所从事的制造业,也就是所谓的制造工作,是指将自己所制造的东西作为形状看得见的工作。在数字化不断发展的时代,只要人们追求便利的生活,需求就不会枯竭,从日常生活中也能了解到为什么需要这样的生活,这也关系到工作的价值。
</div>
 
</body>
</html>

动态背景

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>彩色点缀(鼠标联线)</title>
    <script src="jquery3.5.1.js"></script>
    <style>
    html, body { background: #000; margin: 0; padding:0;}
    canvas { width: 100%; height: 100%; position: absolute; }

    /* Demo Buttons Style */
    .codrops-demos {
        font-size: 0.8em;
        text-align:center;
        position:absolute;
        z-index:99;
        width:96%;
    }

    .codrops-demos a {
        display: inline-block;
        margin: 0.35em 0.1em;
        padding: 0.5em 1.2em;
        outline: none;
        text-decoration: none;
        text-transform: uppercase;
        letter-spacing: 1px;
        font-weight: 700;
        border-radius: 2px;
        font-size: 110%;
        border: 2px solid transparent;
        color:#fff;
    }

    .codrops-demos a:hover,
    .codrops-demos a.current-demo {
        border-color: #383a3c;
    }
    </style>
</head>
<body>
    
    <canvas></canvas>

<script>
    $(function(){
  var canvas = document.querySelector('canvas'),
      ctx = canvas.getContext('2d')
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  ctx.lineWidth = .3;
  ctx.strokeStyle = (new Color(150)).style;

  var mousePosition = {
    x: 30 * canvas.width / 100,
    y: 30 * canvas.height / 100
  };

  var dots = {
    nb: 750,
    distance: 50,
    d_radius: 100,
    array: []
  };

  function colorValue(min) {
    return Math.floor(Math.random() * 255 + min);
  }
  
  function createColorStyle(r,g,b) {
    return 'rgba(' + r + ',' + g + ',' + b + ', 0.8)';
  }
  
  function mixComponents(comp1, weight1, comp2, weight2) {
    return (comp1 * weight1 + comp2 * weight2) / (weight1 + weight2);
  }
  
  function averageColorStyles(dot1, dot2) {
    var color1 = dot1.color,
        color2 = dot2.color;
    
    var r = mixComponents(color1.r, dot1.radius, color2.r, dot2.radius),
        g = mixComponents(color1.g, dot1.radius, color2.g, dot2.radius),
        b = mixComponents(color1.b, dot1.radius, color2.b, dot2.radius);
    return createColorStyle(Math.floor(r), Math.floor(g), Math.floor(b));
  }
  
  function Color(min) {
    min = min || 0;
    this.r = colorValue(min);
    this.g = colorValue(min);
    this.b = colorValue(min);
    this.style = createColorStyle(this.r, this.g, this.b);
  }

  function Dot(){
    this.x = Math.random() * canvas.width;
    this.y = Math.random() * canvas.height;

    this.vx = -.5 + Math.random();
    this.vy = -.5 + Math.random();

    this.radius = Math.random() * 2;

    this.color = new Color();
    console.log(this);
  }

  Dot.prototype = {
    draw: function(){
      ctx.beginPath();
      ctx.fillStyle = this.color.style;
      ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
      ctx.fill();
    }
  };

  function createDots(){
    for(i = 0; i < dots.nb; i++){
      dots.array.push(new Dot());
    }
  }

  function moveDots() {
    for(i = 0; i < dots.nb; i++){

      var dot = dots.array[i];

      if(dot.y < 0 || dot.y > canvas.height){
        dot.vx = dot.vx;
        dot.vy = - dot.vy;
      }
      else if(dot.x < 0 || dot.x > canvas.width){
        dot.vx = - dot.vx;
        dot.vy = dot.vy;
      }
      dot.x += dot.vx;
      dot.y += dot.vy;
    }
  }

  function connectDots() {
    for(i = 0; i < dots.nb; i++){
      for(j = 0; j < dots.nb; j++){
        i_dot = dots.array[i];
        j_dot = dots.array[j];

        if((i_dot.x - j_dot.x) < dots.distance && (i_dot.y - j_dot.y) < dots.distance && (i_dot.x - j_dot.x) > - dots.distance && (i_dot.y - j_dot.y) > - dots.distance){
          if((i_dot.x - mousePosition.x) < dots.d_radius && (i_dot.y - mousePosition.y) < dots.d_radius && (i_dot.x - mousePosition.x) > - dots.d_radius && (i_dot.y - mousePosition.y) > - dots.d_radius){
            ctx.beginPath();
            ctx.strokeStyle = averageColorStyles(i_dot, j_dot);
            ctx.moveTo(i_dot.x, i_dot.y);
            ctx.lineTo(j_dot.x, j_dot.y);
            ctx.stroke();
            ctx.closePath();
          }
        }
      }
    }
  }

  function drawDots() {
    for(i = 0; i < dots.nb; i++){
      var dot = dots.array[i];
      dot.draw();
    }
  }

  function animateDots() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    moveDots();
    connectDots();
    drawDots();

    requestAnimationFrame(animateDots);	
  }

  $('canvas').on('mousemove', function(e){
    mousePosition.x = e.pageX;
    mousePosition.y = e.pageY;
  });

  $('canvas').on('mouseleave', function(e){
    mousePosition.x = canvas.width / 2;
    mousePosition.y = canvas.height / 2;
  });

  createDots();
  requestAnimationFrame(animateDots);	
});
</script>
</body>
</html>

引用的 jquery 文件在 180 的阿里云盘 备份文件/source/htmljs/第三方/jquery3.5.1.js

项目与工程

获取用户选择的文本

const getSelectedText = () => window.getSelection().toString();
getSelectedText();

回到顶部

const goToTop = () => window.scrollTo(0, 0);
goToTop();

获取项目名称

function getProjectName(){
  const strArray = window.location.pathname.split('/');
  return strArray[1];
}

获取URL

console.log(`下面是各种获取URL的方法:`);
console.log(`document.domain:${document.domain}`);//结果是:localhost
console.log(`window.location.host:${window.location.host}`);//结果是:localhost:8080
console.log(`window.location.href:${window.location.href}`);//结果是:http://localhost:8080/PADEMIS/toCpprocess.do
console.log(`self.location.href:${self.location.href}`);//结果:http://localhost:8080/PADEMIS/toCpprocess.do
console.log(`document.URL:${document.URL}`);//结果 - http://localhost:8080/PADEMIS/toCpprocess.do
console.log(`document.location:${document.location}`);//结果 - http://localhost:8080/PADEMIS/toCpprocess.do

若url= 'http://www.baidu.com:8080/cd/a?a=1&b=2#active'
则:
window.location.href => 'http://www.baidu.com:8080?a=1&b=2#active'
window.location.protocol=>'http'
window.location.port=>8080
window.location.search=>'?a=1&b=2'
window.location.pathname=>'/cd/a'
window.location.hash=>'#active'

获取页面参数

// jquery 方式
// 下面代码的调用方法:const code = $.request.queryString["code"];
$.request = (function () { 
    var apiMap = {}; 
    function request(queryStr) { 
        var api = {}; 
        if (apiMap[queryStr]) { return apiMap[queryStr]; } 
        api.queryString = (function () { 
            var urlParams = {}; 
            var e, 
            d = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); }, 
            q = queryStr.substring(queryStr.indexOf('?') + 1), 
            r = /([^&=]+)=?([^&]*)/g; 
            while (e = r.exec(q))     urlParams[d(e[1])] = d(e[2]);
            return urlParams; 
        })(); 
        api.getUrl = function () { 
            var url = queryStr.substring(0, queryStr.indexOf('?') + 1); 
            for (var p in api.queryString) { url += p + '=' + api.queryString[p] + "&";        } 
            if (url.lastIndexOf('&') == url.length - 1) { return url.substring(0, url.lastIndexOf('&')); } 
            return url; 
        } 
        apiMap[queryStr] = api; 
        return api; 
    } 
    $.extend(request, request(window.location.href)); 
    return request; 
})();

html引用js

<!-- 如果 js 文件在当前 html 同级别名称为 src 的目录下,则引用代码是:-->
<script  src="src/jquery-3.5.1.min.js"></script>
<!-- 如果 js 和 html 同级别则引用代码是:-->
<script  src="jquery-3.5.1.min.js"></script>

动态加载 js

$(function(){
    loadFrScript();
})

function loadFrScript(){
    let script = document.createElement("script");
    script.type = "text/javascript";
    script.src = getFineReportUrl();
    document.body.appendChild(script);
}

function getFineReportUrl(){
    const wit
    hProtocol = window.location.href;
    const arr = withProtocol.split(':');
    const protocol = arr[0];

    const hostAndPort = window.location.host;
    return `${protocol}://${hostAndPort}/fr/ReportServer?op=emb&resource=finereport.js`;
}

打印div中的内容

<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
<body>

<script language="javascript">
    function printdiv(printpage) {
        var headstr = '<html><head><title>销售发货单</title></head><body>';
        var footstr = "</body>";
        var newstr = document.getElementById(printpage).innerHTML;
        var oldstr = document.body.innerHTML;
        document.body.innerHTML = headstr + newstr + footstr;

        console.log(headstr + newstr + footstr)
        window.print();
        document.body.innerHTML = oldstr;
        return false;
    }
</script>
<h1>div前</h1>
<div id="div_print">
    <div style="line-height: 30px; color:#000;" class=size16 align=center>
        <strong>销售发货单-01</strong></div>
    <table border=0 cellspacing=0 cellpadding=0 width="100%">
        <tbody>
        <tr>
            <td width="43%">所在店铺:<span>XYZ-专卖店</span></td>
            <td width="33%">发货单号:<span>2020050810372</span></td>
            <td>快递单号:</td>
        </tr>
        <tr>
            <td>收 件 人:<span>小明</span></td>
            <td>网店单号:<span>74235823905643</span</td>
            <td>发货日期:2020-5-10</td>
        </tr>
        <tr>
            <td>电话号码:<span>13935429860 </span></td>
            <td>收件人id:<span>小李飞刀</span></td>
            <td> </td>
        </tr>
        </tbody>
    </table>
    <table border=1 cellspacing=0 cellpadding=1 width="100%" style="border-collapse:collapse" bordercolor="#333333">
        <thead>
        <tr>
            <td width="10%">
                <div align=center><b>表格页眉</b></div>
            </td>
            <td width="25%">
                <div align=center><b>品名</b></div>
            </td>
            <td width="10%">
                <div align=center><b>颜色</b></div>
            </td>
            <td width="10%">
                <div align=center><b>规格</b></div>
            </td>
            <td width="10%">
                <div align=center><b>数量</b></div>
            </td>
            <td width="15%">
                <div align=center><b>单价</b></div>
            </td>
            <td width="20%">
                <div align=center><b>金额</b></div>
            </td>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td> 1</td>
            <td>名称01</td>
            <td>浅灰色</td>
            <td>185/10</td>
            <td>1</td>
            <td>248.00</td>
            <td>248.00</td>
        </tr>
        <tr>
            <td> 2</td>
            <td>名称02</td>
            <td>浅灰色</td>
            <td>185/10</td>
            <td>1</td>
            <td>248.00</td>
            <td>248.00</td>
        </tr>
        <tr>
            <td> 3</td>
            <td>名称03</td>
            <td>浅灰色</td>
            <td>185/10</td>
            <td>1</td>
            <td>248.00</td>
            <td>248.00</td>
        </tr>
        <tr>
            <td> 4</td>
            <td>名称04</td>
            <td>浅灰色</td>
            <td>185/10</td>
            <td>1</td>
            <td>248.00</td>
            <td>248.00</td>
        </tr>
    </table>
    <input name="btn_print" type="button" onclick="printdiv('div_print');" value="打印" align=center>
</div>
<h1>div后</h1>
</body>
</html>

页面加载后运行

在 html 页面加载完毕后立即开始运行

// 纯 js 的立即运行
(function(){
  console.log('立即运行了吗?');
})();

// jquery 的立即运行
$(function(){
  console.log('jquery的加载后运行')
});

流程控制

for

// 循环5次
for (let i = 0; i < 5; i++) {

}

// 遍历对象的属性
for (const key in obj) {

}
for (const item of obj) {

}

工具函数

枚举体最佳实践

下面是 javascript 枚举体

const Color = Object.freeze({
  RED: 'RED',
  GREEN: 'GREEN',
  BLUE: 'BLUE'
});

// 使用,本方法创建的对象不可修改,其中数据也不可修改
console.log(Color.RED); // 'RED'

// 也可以通过 Symbol 创建不可修改的枚举体
const Direction = Object.freeze({
  UP: Symbol('UP'),
  DOWN: Symbol('DOWN'),
  LEFT: Symbol('LEFT'),
  RIGHT: Symbol('RIGHT')
});

// 使用
const move = (direction) => {
  switch(direction) {
    case Direction.UP: // ...
  }
}

下面是 TypeScript 枚举体

// TypeScript 原生枚举
enum LogLevel {
  ERROR,
  WARN,
  INFO,
  DEBUG
}

// 或字符串枚举
enum Direction {
  Up = "UP",
  Down = "DOWN"
}


// 下面是带有额外功能的增强枚举体
class Enum {
  constructor(...keys) {
    keys.forEach((key, i) => {
      this[key] = key;
      this[i] = key;
    });
    Object.freeze(this);
  }
  
  *[Symbol.iterator]() {
    for (let key of Object.keys(this)) {
      if (!isNaN(Number(key))) continue;
      yield this[key];
    }
  }
}

const Size = new Enum('SMALL', 'MEDIUM', 'LARGE');

ifNull

/**
 * 传入第一个参数 originalData 如果是 “空” 则返回后面的第二个参数
 * 相反则返回原始数据 originalData
 */
function ifNull(originalData,newData){
    return (originalData == "" || originalData == undefined || originalData == null || originalData == NaN) ? newData : originalData;
}

获取路径参数

下面是通过正则表达式的方式获取 url 参数的方法

// 传入url,则取其中的参数
// 传入url = 空字符串则取当前页面的 url 的参数
function getQueryParam(url,param) {
    let queryString = '';
		if(!url || url.length === 0) queryString = location.search;
		else queryString = url;
		
    const regex = new RegExp(`[?&]${param}=([^&]+)`);
    const match = queryString.match(regex);
    return match ? decodeURIComponent(match[1]) : null;
}

const url = 'https://example.com/page?name=John&age=30';
const name = getQueryParam(url,'name'); // 返回 "John"
const age = getQueryParam(url,'age');   // 返回 "30"

console.log(name, age); // 输出: John 30

拷贝内容到剪贴板

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <title>语音播报</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <button onclick="copyToClip('chanchaw1111','you did')"> Copy </button>
    <script type="text/javascript">
            /**
         * 复制内容到粘贴板
         * content : 需要复制的内容
         * message : 复制完后的提示,不传则默认提示"复制成功"
         */
        function copyToClip(content, message) {
            var aux = document.createElement("input"); 
            aux.setAttribute("value", content); 
            document.body.appendChild(aux); 
            aux.select();
            document.execCommand("copy"); 
            document.body.removeChild(aux);
            if (message == null) {
                alert("复制成功");
            } else{
                alert(message);
            }
        }
    </script>
</body>

数据相关

进制转换

const num = 43
const binaryNum = num.toString(2)
const hex = num.toString(16)

UUID

function getUUID(){
  const newUUID =('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  var r = Math.random() * 16 | 0,
  v = c == 'x' ? r : (r & 0x3 | 0x8);
  return v.toString(16);
  }));

  return newUUID;
}

function getUUIDNoSymbol(){
  const rawUUID = getUUID();
  const newUUID = rawUUID.replace(/-/g,'');
  return newUUID;
}

计算误差

console.log(2-1.6);
计算的结果是:0.3999999999999999
JS中解决:change.toFixed(2);// 保留两位小数

浏览器标签页图标

<head>
	<link rel="shortcut icon" href="./assets/favicon.ico" type="image/x-icon" />
</head>