一些小知识点

 

/**
 * 计算字符串所占的内存字节数,默认使用UTF-8的编码方式计算,也可制定为UTF-16
 * UTF-8 是一种可变长度的 Unicode 编码格式,使用一至四个字节为每个字符编码
 * 
 * 000000 - 00007F(128个代码)      0zzzzzzz(00-7F)                             一个字节
 * 000080 - 0007FF(1920个代码)     110yyyyy(C0-DF) 10zzzzzz(80-BF)             两个字节
 * 000800 - 00D7FF 
   00E000 - 00FFFF(61440个代码)    1110xxxx(E0-EF) 10yyyyyy 10zzzzzz           三个字节
 * 010000 - 10FFFF(1048576个代码)  11110www(F0-F7) 10xxxxxx 10yyyyyy 10zzzzzz  四个字节
 * 
 * 注: Unicode在范围 D800-DFFF 中不存在任何字符
 * {@link http://zh.wikipedia.org/wiki/UTF-8}
 * 
 * UTF-16 大部分使用两个字节编码,编码超出 65535 的使用四个字节
 * 000000 - 00FFFF  两个字节
 * 010000 - 10FFFF  四个字节
 * 
 * {@link http://zh.wikipedia.org/wiki/UTF-16}
 * @param  {String} str 
 * @param  {String} charset utf-8, utf-16
 * @return {Number}
 */
export function byteCompute(str, charset) {
  var total = 0,
    charCode,
    i,
    len;
  charset = charset ? charset.toLowerCase() : '';
  if (charset === 'utf-16' || charset === 'utf16') {
    for (i = 0, len = str.length; i < len; i++) {
      charCode = str.charCodeAt(i);
      if (charCode <= 0xffff) {
        total += 2;
      } else {
        total += 4;
      }
    }
  } else {
    for (i = 0, len = str.length; i < len; i++) {
      charCode = str.charCodeAt(i);
      if (charCode <= 0x007f) {
        total += 1;
      } else if (charCode <= 0x07ff) {
        total += 2;
      } else if (charCode <= 0xffff) {
        total += 3;
      } else {
        total += 4;
      }
    }
  }
  return total;
}

 

 

 

 

 横向滚动,图片都在中间

 

 

.container {
  display: flex;
  gap: 20px;
  box-shadow: 0 3px 10px 0 rgba(0 0 0 / 0.1);
  border-radius: 5px;
  padding: 20px;
  width: 640px;
  position: relative;
  scroll-behavior: smooth;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  scroll-snap-type: x mandatory;
  scroll-padding: 20px;
}

img {
  border-radius: 4px;
  max-height: 300px;
  width: auto;

  scroll-snap-align: center;
  scroll-snap-stop: always;
}

  

 

 

cookie 增查

<!--1.语义化标签的作用-->
<!--1.1 从开发角度考虑是提高代码的可读性可维护性-->
<!--1.2 网站的发布者:seo 搜索引擎优化 -->

<!--2.语义化标签的兼容问题-->
<!--2.1 IE9以下不支持H5标签(大部分css3属性,一些H5的api)-->
<!--2.2 IE9以下不认识,把这些标签当做行内元素去看待-->
<!--2.3 语义化标签需要动态创建 document.createElement('header') 同时设置块级元素-->
<!--2.4 有一款插件能帮你完成这件事件  html5shiv.js   -->
<!--2.5 必须引入在头部,在页面结构之前,提前解析h5标签-->
<!--2.6 优化处理:支持H5标签的不需要加载,IE9以下不支持H5加载-->
<!--2.7 js判断客户的浏览器版本可以做到,但是不能做到js提前加载-->
<!--2.8 条件注释:网页的任何地方  根据浏览器版本去加载内容(html标签)-->
<!--2.9 固定语法  lt 小于  gt 大于  lte 小于等于  gte 大于等于 -->

条件注释

<!--[if lte IE 8]>
<script src="html5shiv.min.js"></script>
<![endif]-->

 

获取最近个月的时间
import moment from 'moment';
// 默认选择时间为最近7天
 const defaultSelectDate = {
    startDate: moment().startOf('day').subtract(6, 'days').format("YYYY-MM-DD"),
    endDate: moment().endOf('day').format("YYYY-MM-DD")
  }
  // 选择时间限制,区间是今天往前的3个月,也就是最近三个月
  const limitSelectDate = {
    min: moment().startOf('day').subtract(1, 'months').format("YYYY-MM-DD"),
    max: moment().endOf('day').format("YYYY-MM-DD")
  }

defaultSelectDate {startDate: "2019-09-19", endDate: "2019-09-25"}
 limitSelectDate {min: "2019-08-25", max: "2019-09-25"}

 

js 时间格式转换
<script type="text/javascript">
    // 获取当前时间戳(以s为单位)
     var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    //当前时间戳为:1403149534
     console.log("当前时间戳为:" + timestamp);
    // 获取某个时间格式的时间戳
    var stringTime = "2018-07-10 10:21:12";
    var timestamp2 = Date.parse(new Date(stringTime));
    timestamp2 = timestamp2 / 1000;
    //2018-07-10 10:21:12的时间戳为:1531189272
    console.log(stringTime + "的时间戳为:" + timestamp2);
    // 将当前时间换成时间格式字符串
     var timestamp3 = 1531189272;
     var newDate = new Date();
     newDate.setTime(timestamp3 * 1000);
    // Wed Jun 18 2018
    console.log(newDate.toDateString());
    // Wed, 18 Jun 2018 02:33:24 GMT
     console.log(newDate.toGMTString());
    // 2018-06-18T02:33:24.000Z
    console.log(newDate.toISOString());
    // 2018-06-18T02:33:24.000Z
    console.log(newDate.toJSON());
    // 2018年6月18日
    console.log(newDate.toLocaleDateString());
    // 2018年6月18日 上午10:33:24
    console.log(newDate.toLocaleString());
    // 上午10:33:24
     console.log(newDate.toLocaleTimeString());
    // Wed Jun 18 2018 10:33:24 GMT+0800 (中国标准时间)
    console.log(newDate.toString());
    // 10:33:24 GMT+0800 (中国标准时间)
    console.log(newDate.toTimeString());
     // Wed, 18 Jun 2018 02:33:24 GMT
     console.log(newDate.toUTCString());
Date.prototype.format = function(format) {
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
    for (var k in date) {
       if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
       }
     }
     return format;
 }
 console.log(newDate.format('yyyy-MM-dd h:m:s'));
 </script>

 

H5 知识

H5 api
1. querySelector() 获取符合选择器的第一个元素
2. querySelectorAll() 获取符合选择器的所有元素

1. jquery操作类的方法:addClass() removeClass() toggleClass() hasClass()
2. h5也有类似的api 基于一个对象classList的方法 add() remove() toggle() contains()     //contains判断有误类,返回布尔值

eg:
<script>
    var dom = document.querySelector('li:nth-child(2)');
    /*1.获取类*/
    console.log(dom.classList);
    /* DOM.classList  获取的是这个DOM元素上的所有class */
    /*2.操作类*/
    dom.classList.add('blue');
    dom.classList.remove('red');

    document.querySelector('button').onclick = function () {
        dom.classList.toggle('toggle');
        console.log(dom.classList.contains('red'));
    }
</script>

H5自定义属性 : date-*
H5的date-*属性: 更改的是DOM
  var div= document.querySelector('div') //获取
  div.dateset //获取元素的所有date 对象
  div.dateset.user //获取单个

jQuery的date-*属性 : 更改的是内存(对象存储的位置内存,并不修改DOM)
$('div').date() //获取所有date属性
$('div').date('user')    // 获取单个
$('div').date('user','16')  //设置属性值
 

 

<meta http-equiv="refresh" content="0; url=">    404重定向
页面定期刷新,如果加url的,则会重新定向到指定的网页,content后面跟的是时间(单位秒),把这句话加到指定网页的<head></head>

 分享到Facebook links yotube

  <div class=fx><a class=fb href="javascript:window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(document.location.href)+'&t='+encodeURIComponent(document.title),'_blank','toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, width=600, height=450,top=100,left=350');void(0)"></a>
            <a class=ytb href=#></a> <a class=tw href="javascript:window.open('http://twitter.com/home?status='+encodeURIComponent(document.location.href)+' '+encodeURIComponent(document.title),'_blank','toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, width=600, height=450,top=100,left=350');void(0)"></a>
            <a class=in href="javascript:window.open('http://www.linkedin.com/shareArticle?mini=true&url='+encodeURIComponent(document.location.href)+'&title='+encodeURIComponent(document.title)+'&source='+encodeURIComponent(document.location.href),'_blank','toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, width=600, height=450,top=100,left=350');void(0)"></a>
        </div>

 

JsFormat:

这里下载这插件包 https://github.com/jdc0589/JsFormat ,点油下角的zip就能下载

使用方法:

1、快捷键:ctrl+alt+f

 

html-css-js prettify:

1、快捷键:ctrl+shift+P

3、输入html-css-js prettify,选择html-css-js prettify

 

  https://chenhuichao.com/    陈回潮的学习博客

//安装ruby 配置sass 环境

移除之前的环境,使用国内镜像
gem sources --add https://gems.ruby-china.com/ --remove https://rubygems.org/

//安装完成之后,查看源
gem sources -l

//提示如下

*** CURRENT SOURCES ***

https://gems.ruby-china.com/

gem install sass


编译参数:--no-cache %FileName% %FileBaseName%.css --style compact
参考链接:https://gems.ruby-china.com/

 

滚动到页头
<script>

        $(window).scroll(function(){
      $("#scrolls").click(function(){
            $("html, body").animate({scrollTop:0 },300);
        })
    });
    </script>

 

监听span里面text 文本的变化触发事件
$("#select2-chosen-6").bind("DOMNodeInserted",function(e){ console.log($(e.target).html()); })

 jquery : stickUp

 

#获取访问用户的IP地址
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script> 

      document.write(returnCitySN["cip"]+','+returnCitySN["cname"])

 

 $.ajax({

             type: "POST",

             url: "test.json",

             data: {ip:'168.122.122.12'},

             dataType: "json",

             success: function(data){

            }

         });

 

请求轮询:数据实时更新——每隔xx秒需要刷新一次接口——即需要用到定时器相关原理,只使用setInterval 会造成定时器叠加,致页面卡死
window.setInterval(() => { setTimeout(fun, 0) }, 30000)

 

//点击遮罩层隐藏,解决方案是便是判断event target ,并且保证 这个时间不会冒泡。
$('.overlay').click(function(e){ if (e.target == e.currentTarget) closeOverlay(); });

 

cookie小记
//判断cookie是否存在
getCookie(name)      
        {
            var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
            if(arr != null) {
                this.options=JSON.parse(arr[2])
            }else{
                this.getScreen()
            }
        }

//设置增加cookie   params: exdays(定时过期)
设置定cookie 为数组内含对象时需要转换为字符串 eg: var data=[{a:1},{a:2}]
JSON.stringify(data)

setCookie(c_name,exdays) { var exdate = new Date(); exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); window.document.cookie = "secondCategory" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString(); }

 

修改滚动条样式
/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/  
::-webkit-scrollbar  
{  
    width: 4px;  /*滚动条宽度*/
    height: 10px;  /*滚动条高度*/
}  
  
/*定义滚动条轨道 内阴影+圆角*/  
::-webkit-scrollbar-track  
{  
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);  
    border-radius: 10px;  /*滚动条的背景区域的圆角*/
    background-color: #eee;/*滚动条的背景颜色*/  
}  
  
/*定义滑块 内阴影+圆角*/  
::-webkit-scrollbar-thumb  
{  
    border-radius: 10px;  /*滚动条的圆角*/
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);  
    background-color: #999;  /*滚动条的背景颜色*/
}  

 

// 对象深度克隆方法
export function cloneObj(obj) {
  let str;
  let newobj = obj.constructor === Array ? [] : {};
  if (typeof obj !== 'object') {
    return;
  } else if (window.JSON) {
    str = JSON.stringify(obj); // 序列化对象
    newobj = JSON.parse(str); // 还原
  } else {
    // 如果不支持以上方法
    for (const i in obj) {
      if ({}.hasOwnProperty.call(obj, i)) {
        newobj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i];
      }
    }
  }
  return newobj;
}

 邮箱校验:
REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"

 

当前分支是maser分支,我想将stable分支上的代码完全覆盖brush分支,首先切换到brush分支。

git reset --hard origin/stable

检查元素是否在视窗内

// 计算两个时间搓的差时
function getInterval(start, end) {
           //两个日期对象,相差的毫秒数
           var interval = end - start;
           // 两个日期对象,相差的秒数
           // interval = interval / 1000;
           interval /= 1000;
           //求相差的天数/小时数/分钟数/秒数
           var day, hour, minute, second;
           day = Math.round(interval / 60 / 60 / 24);
           hour = Math.round(interval / 60 / 60 % 24);
           minute = Math.round(interval / 60 % 60);
           second = Math.round(interval % 60);
           return {
               day: day,
               hour: hour,
               minute: minute,
               second: second
           }
       }

 

//时间格式化
1.
var date= new Date(); //获取日期
var year=date.getFullYear(); //获取年份
var month=date.getMonth()+1; //获取月份
var day=date.getDate(); //获取天
var hour=date.getHours(); //获取时
var minute=date.getMinutes(); //获取分
var second=date.getSeconds(); //获取秒
var weekday=date.getDay(); //获取周
var week=new Array(7); //数组
week[0]=‘周日’;


2.
var unixTimestamp = new Date( 1477386005*1000 ) ;
commonTime = unixTimestamp.toLocaleString();
Date.prototype.toLocaleString = function() {
          return this.getFullYear() + "年" + (this.getMonth() + 1) + "月" + this.getDate() + "日 " + this.getHours() + "点" + this.getMinutes() + "分" + this.getSeconds() + "秒";
    };

 

console 的常用方法
1. 计算操作占用时长
console.time('timer');
console.timeEnd('timer');
2.console.table() 将数据以表格的形式显示
3.console.count() 此函数接受一个可选参数 label // 输出被调用的次数

 

// 当前的时间 x 随机数
function tid() {
const mydate = new Date()
const uuids = mydate.getDay() + mydate.getHours() + mydate.getMinutes() + mydate.getSeconds() + mydate.getMilliseconds() + Math.round(Math.random() * 10000);
return uuids
}
// 4位的随机数
function rid() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
// 再组合4个4位随机数
export function uuid() {
return (tid() + "_" + rid() + "_" + rid() + "_" + rid())
}

 

    <script>
        sessionStorage.setItem('reload', 1)
        window.addEventListener('error', function (event) {
            try {
                const msg = event.message
                const unToken = /Unexpected token/.test(msg) && /</.test(msg) && /Uncaught SyntaxError/.test(msg)
                const chunkFailed = /ChunkLoadError/.test(msg) && /Loading chunk/.test(msg) && /failed/.test(msg)
                let firstReload = sessionStorage.getItem('reload')
                if ((chunkFailed || unToken) && (Number(firstReload) <= 5)) {
                    sessionStorage.setItem('reload', Number(firstReload) + 1)
                    window.location.reload()
                }
            } catch (err) {
                console.log('e', err)
            }
        })
    </script>

 

// 简单骨架屏
<div class="card">
  <div class="image">
    <img src="https://assets.codepen.io/2002878/wake-up-and-code.jpg" alt="">
  </div>
  <div class="content">
    <h4>CodingStartup</h4>
    <div class="description">
      Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ex quasi enim facere commodi omnis...
    </div>
  </div>
</div>

<div class="card loading">
  <div class="image">
    dsada
  </div>
  <div class="content">
    <h4></h4>
    <div class="description">
      
    </div>
  </div>
</div>

css ---
:root {
  --loading-grey: #ededed;
}

body {
  background-color: #f6f6f6;
  font-family: Helvetica;
  font-size: 15px;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  min-height: 100vh;
}

.card {
  width: 320px;
  background-color: #fff;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0px 4px 6px rgba(0, 0, 0, .12);
}

.image {
  height: 200px;
}

.image img {
  display: block;
  width: 100%;
  height: inherit;
  object-fit: cover;
}

.content {
  padding: 2rem 1.8rem;
}

h4 {
  margin: 0 0 1rem;
  font-size: 1.5rem;
  line-height: 1.5rem;
}

.description {
  font-size: 1rem;
  line-height: 1.4rem;
}

.loading .image,
.loading h4,
.loading .description {
  background-color: var(--loading-grey);
  background: linear-gradient(
    100deg,
    rgba(255, 255, 255, 0) 40%,
    rgba(255, 255, 255, .5) 50%,
    rgba(255, 255, 255, 0) 60%
  ) var(--loading-grey);
  background-size: 200% 100%;
  background-position-x: 180%;
  animation: 1s loading ease-in-out infinite;
}

@keyframes loading {
  to {
    background-position-x: -20%;
  }
}

.loading h4 {
  min-height: 1.6rem;
  border-radius: 4px;
  animation-delay: .05s;
}

.loading .description {
  min-height: 4rem;
  border-radius: 4px;
  animation-delay: .06s;
}

rem自适应布局
通常将rem布局比例设置成1rem=100px,即在设计图上100px长度在CSS代码上使用1rem表示。

function AutoResponse(width = 750) {
    const target = document.documentElement;
    if (target.clientWidth >= 600) {
        target.style.fontSize = "80px";
    } else {
        target.style.fontSize = target.clientWidth / width * 100 + "px";
    }
}
AutoResponse();
window.addEventListener("resize", () => AutoResponse());
当然还可依据屏幕宽度设计图宽度的比例使用calc()动态声明<html>font-size,这样就能节省上述代码。不对,是完全代替上述代码。

html { font-size: calc(100vw / 7.5); }

  

 

posted @ 2019-03-08 15:09  dobinspark  阅读(424)  评论(0编辑  收藏  举报