js 2017

JS面向对象

<script>
  function num(val) {
    return val * 8
  }
  function Index(name, age) {
    this.name = name;
    this.age = age;
  }
  Index.prototype = {
    constructor: Index
  }
  Index.prototype.test = function () {
    console.log(num(this.age));
  }
  Index.prototype.testB = function () {
    console.log(num(this.name));
  }

  var a = new Index('kang', 22)
  a.test()
  a.testB()
</script>
View Code

 js面向对象推荐写法

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script>
  var Index = function (name, age) {
    this.name = name;
    this.age = age;
  }
  Index.prototype = {
    constructor: Index,
    num: function (val) {
      return val + 28
    },
    testA: function () {
      console.log(this.num(this.age));
    },
    testB: function () {
      console.log(this.num(this.name));
    },
    testC: (function () {
      console.log(111);
    })()
  }
  var a = new Index('kang', 252)
  a.testA()
  a.testB()
</script>
</body>
</html>

自调用函数 

<script>
  !function (a, b) {
    console.log(a + b)
  }(1, 2);

  (function (c, d) {
    console.log(c + d)
  })(3, 4)
  // 你甚至可以在function前面加一元操作符号
  !function () { /* code */ } ();
  ~function () { /* code */ } ();
  -function () { /* code */ } ();
  +function () { /* code */ } ();
</script>
View Code

 jq $.get('a.json') 读取json  $.grep()过滤json

<script>
  $.get('xx.json', function (res) {
    // 过滤数据
    var res = $.grep(res, function (n) {
      return n.value.length == 2 // 过滤条件
    })
  }, 'json')
</script>

 模板引擎 arttemplate

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
https://github.com/aui/art-template/blob/master/lib/template-web.js
<script id="test" type="text/html">
  <h1>{{title}}</h1>
  <ul>
    {{each list as value i}}
    <li>索 {{i + 1}} :{{value}}</li>
    {{/each}}
  </ul>
</script>
<div id="content"></div>
<script src="template-web.js"></script>
<script>
  var data = {
    title: '标签123',
    list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他']
  };
    var html = template('test', data);
    document.getElementById('content').innerHTML = html;
</script>
</body>
</html>
View Code

 sha1

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<!--
加密前的明文为:000714804762308511eb58071dde449179a3a2745fc9f1e77
加密后的结果为:
fae96b30c78e386f32df9d286905bf87b92e1a3d
-->
<script src="https://cdn.bootcss.com/crypto-js/3.1.9/crypto-js.min.js"></script>
<script>
  var val = '000714804762308511eb58071dde449179a3a2745fc9f1e77'
  var res = CryptoJS.SHA1(val)
  alert(res)   // 正确
  console.log(res);  // 控制台输入出错
  document.write(res); // 正确
</script>
</body>
</html>
View Code

 jq表单提交,reset不刷新数据   

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
表单重置阻止刷新页面
<form id="form1">
  <select name="" id="">
    <option value="">---请选择---</option>
    <option value="">s</option>
    <option value="">s333</option>
  </select>
  <button>btn</button>
  <input type="text" placeholder="abc">
</form>
<script src="jquery.min.js"></script>
<script>
  $("button").click(function () {
    return test()  // 返回函数
  })
  function test() {
    $("form")[0].reset();
    return false  // 返回 false
  }
</script>
</body>
</html>
View Code

 js变量作用域    在test()函数内先声明变量b,再执行 输出,为 undefined,再为b赋值3 

 var b = 10;
  function test() {
    console.log(b);  // undefined
    var b = 3;
  }
  test()

事件委托,减少事件

<body>
页面的事件处理程序(点击事件等)太多会影响页面性能,每个函数是对象,占内存,性能差,必须事先指定所有事件处理程序而导致DOM访问次数,
延迟整个页面的交互就绪时间。
使用事件委托,
<div class="a">
  <div class="b">bbb</div>
  <div class="c">bbb</div>
  <div class="d">bbb</div>
</div>
<script>
  // 事件委托,减少事件
  document.getElementsByClassName('a')[0].addEventListener('click', function (e) {
    var name = e.target.className;
    switch (name) {
      case 'b':
        console.log('bbb');
        break;
      case 'c':
        console.log('ccc');
        break;
      case 'd':
        console.log('ddd');
        break;
      default:
        console.log('eee');
    }
  })
</script>
View Code

 表单elements属性     chrome safari支持的H5表单属性 autocomplete autofocus multiple  表单过滤  剪贴板事件

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
<form id="form1">
  <input type="text" name="username">
  <select id="" multiple name="num">多选效果
    <option value="111">中国</option>
    <option value="2">2</option>
  </select>
</form>
<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script>
  //  表单有 elements属性,包含表单所有字段,如 Input textarea等
  var form = document.getElementById('form1');  // document.forms[0]  表单获取方式二
//  form.elements[0]; // 取得表单第一个字段
  //form.elements['username']; // 通过name属性来取得input字段
 // form.elements.length; // 所有字段的长度
  // 避免表单多次提交
  // 通过submit事件来禁用提交按钮
  form.addEventListener('submit', function () {
    btn.disabled = true;
  })
  // option 值
  console.log(form.elements["num"].options[0].text) // 中国
  console.log(form.elements["num"].options[0].value) // 111
</script>
<input type="text" autofocus > // 手机端chrome safari  支持的有 autocomplete autofocus multiple placeholder 少用吧
 14.2.2 过滤输入
  input屏蔽字符编码  P443
  操作剪贴板 P444  opera 不支持前贴板事件
  14.2.3自动切换焦点
</body>
</html>
View Code

 原生拖放dragstart、历史状态管理 history.pushState()  函数错误处理

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
【1】原生拖放事件 ie4就支持了 H5把拖放事件规范化
dragstart   drag    dragend
当元素被手动到一个有效的放置目标上时,下列事件会依次发生:
dragenter  dragover   dragleave或drop
【2】历史状态管理  不刷新页面跳转
history.pushState()   replaceState()
// ie11才支持  pushState()创造的每一个假的 url,在web服务器上必须有一个真的url存在,否则一刷新,会报错
<a href="1.html">1111111</a>
//  history.pushState()
【3】错误处理
关注函数和引发函数执行失败的因素,抛出自定义的错误方便查看  // 感觉没人使用
<script>
function test(arr){
  if(!(arr instanceof Array)){  // 判断参数是数组
    throw new Error('val must be an arr');
  }
  // ...
}
function concat(str1,str2,str3) {
  var res = str1 + str2;
  if (typeof str3 == 'string') {   //  if(str3) 判断不严谨   str3要是string类型才处理
    res += str3;
  }
  return res;
}
function getQueryString(url) {
  if(typeof url == 'string'){  //  判断参数是 string
//    ...
  }
}
function addQueryStringArg(url, name, val) {
  if(url.indexOf("?") == -1){
    url+='?';
  }else {
    url+="&"
  }
  url+= encodeURIComponent(name)+'='+encodeURIComponent(val)
}
var url = 'http://www.baidu.com';
var newUrl = addQueryStringArg(url,'redir','http://www.xxx.com')
  // http://www.baidu.com?redir=http%3A%2F%2Fwww.xxx.com

</script>
【4】把错误记录到服务器  17.2.7 不需要吧?
</body>
</html>
View Code

 百度地图2.0 自定义图标、调整位置

http://lbsyun.baidu.com/jsdemo.htm?a#c1_16

var myIcon = new BMap.Icon(iconUrl, new BMap.Size(20, 23),{   // 图标宽高
      anchor:new BMap.Size(10,23)  // 自定义图标调整位置   第一个值为图标宽度的一半
    })
      var marker = new BMap.Marker(new BMap.Point(Longitude, Latitude), {icon: myIcon});  // 创建标注
View Code
jq判断元素是否含有某样式
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    li {
      list-style: none;
    }
    ul {
      height: 30px;
    }
    ul li {
      line-height: 30px;
      height: 30px;
      display: none;
    }
    ul.on {
      height: auto;
    }
    ul.on li {
      display: block;
    }
    ul.on .btn {
      transform: rotate(180deg);
      -ms-transform: rotate(180deg); /* IE 9 */
      -moz-transform: rotate(180deg); /* Firefox */
      -webkit-transform: rotate(180deg); /* Safari 和 Chrome */
      -o-transform: rotate(180deg); /* Opera */
    }
    .btn:hover {
      cursor: pointer;
    }
  </style>
</head>
<body>
jq判断元素是否含有某样式   $("#xx").attr('class').indexOf('newClass')>0 ? 'yes': 'no'
<ul id="ulList" class="aaa">  // 必须有一个样式,才能判断是否有其他样式
  <li>12341</li>
  <li>12342</li>
  <li>12343</li>
  <li>12344</li>
  <li>12345</li>
  <li>12346</li>
  <img src="arrow.png" alt="" class="btn">
</ul>
<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script>
  $("ul li").eq(0).show();
  $(".btn").click(function () {
    $("#ulList").toggleClass('on')
    if ($("ul").attr('class').indexOf('on') > 0) {  // 如果ul没有aaa 等任何一个样式,则该判断无效
      console.log(11);
    } else {
      console.log(22);
    }
  })
</script>
</body>
</html>
View Code

 图片、背景图放大缩小

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <style type="text/css">
    .box{
      width:300px;height:300px;
      /*url图片途径*/
      background:url(swipe_error.jpg) no-repeat center; border:5px solid #0099CC;
      -webkit-transition:0.5s;
      background-size:500px 500px;
    }
    .box:hover{
      background-size:600px 600px;
    }
  </style>
</head>
<body>
<!-- css 动画  -->
<div class="box"></div>
<script>
  $(document).on('mouseover mouseout', '.xxx', function (e) {
    if (e.type == 'mouseover') {
      $(this).stop().animate({
        backgroundSize: '130%'  //  背景图片放大缩小
        /*  // 图片放大缩小
        *  width:'130%',
        *  height:'130%',
        *  marginLeft:'-15%',
        *  marginTop:'-15%'
        * */
      })
    } else if (e.type == 'mouseout') {
      $(this).stop().animate({
        backgroundSize: '100%'
      })
    }
  })
</script>
</body>
</html>
View Code

 懒加载 jquery.lazyload.min.js

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
  <style>
    .my-lazy{
      /* 默认的占位图 */
      background:url('swipe_error.jpg') no-repeat center;
    }
  </style>
</head>
<body>
<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script src="jquery.lazyload.min.js"></script>
<div style="height:1000px;width:1000px;border: 1px solid green;"></div>
<div class="lazy my-lazy" data-original="swipe_error.jpg" style="width:1920px;height:390px;"></div>
<script>
  $("div.lazy").lazyload()  // 背景图懒加载,  先加载占位图,当滚动到该页面时加载对应背景图
</script>
https://www.w3cways.com/1765.html 插件下载,教程
http://blog.csdn.net/love_gaohz/article/details/46463623  图片懒加载、背景图懒加载
</body>
</html>
View Code

 上下移动表格行

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .danger{
      color: red;
    }
  </style>
</head>
<body>
<table class="table" id="test_table">
  <thead>
  <tr>
    <th>时间</th>
    <th>详情</th>
    <th>操作</th>
  </tr>
  </thead>
  <tbody>
  <tr cid="7.0.0-2014-04-29_11-02-24_123" class="list_line">
    <td>
      2014-04-29 11:02:24
    </td>
    <td>
      详情
    </td>
    <td>
      <span class="move_btn glyphicon glyphicon-arrow-up" move_act="up">1</span>
      <span class="move_btn glyphicon glyphicon-arrow-down" move_act="down">2</span>
    </td>
  </tr>
  <tr cid="7.0.0-2014-04-29_11-02-24_915" class="list_line">
    <td>
      2014-04-28 10:00:00
    </td>
    <td>
      详情
    </td>
    <td>
      <span class="move_btn glyphicon glyphicon-arrow-up" move_act="up">1</span>
      <span class="move_btn glyphicon glyphicon-arrow-down" move_act="down">2</span>
    </td>
  </tr>
  </tbody>
</table>
</body>
</html>
<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
  $(function(){
    $('.move_btn').click(function(){
      var move_act = $(this).attr('move_act');
      $('#test_table tbody tr').removeClass('danger');

      if(move_act == 'up'){
        $(this).parent().parent('tr').addClass('danger')
          .prev().before($(this).parent().parent('tr'));
      }
      else if(move_act == 'down'){
        $(this).parent().parent('tr').addClass('danger')
          .next().after($(this).parent().parent('tr'));
      }
      setTimeout("$('#test_table tbody tr').removeClass('danger');", 2000);
    });
  });
</script>
View Code

 请求头option 

假如我在http://localhost:8081/访问使用json-server在http://localhost:3000/模拟的API,这应该算是跨域吧,使用POST是时,在控制台就会出现“2次”请求,第一次为OPTIONS请求,第二次才是POST请求。我查了下这叫做Preflighted Requests(预检请求),当发生跨域请求时,fetch会先发送一个OPTIONS请求,来确认服务器是否允许接受请求。服务器同意后,才会发送真正的请求。
    只要是带自定义header的跨域请求,在发送真实请求前都会先发送OPTIONS请求,浏览器根据OPTIONS请求返回的结果来决定是否继续发送真实的请求进行跨域资源访问。

 手机自适应方案

!function (doc, win) {  // 自调用函数并传参
      var docEl = doc.documentElement,  //  得到当前页面所有的 html代码
      resizeEvt = "orientationchange" in window ? "orientationchange" : "resize",  // pc端结果永远为 resize?可能要在手机上才能看到效果  手机横竖屏事件  orientation方向
        // 微信内置浏览器,手机横竖屏无效果, UC浏览器有横竖屏效果, 微信结果为 resize
      recalc = function (num) {
        document.write(num);
        var width = docEl.clientWidth;  //  得到客户区宽度,即内容+padding ,即手机/pc屏幕的宽度 375等
        width = width > 750 ? 750 : width;
        console.log(width);
          width && (docEl.style.fontSize = 100 * (width / 375) + "px")  // 设置 html的字体大小   如果width为假,则后面不会执行
        };
      if (doc.addEventListener) {  // 怎么验证这些事件什么时候触发呢?  PC/手机都会执行3个事件
        document.write(resizeEvt);
        win.addEventListener(resizeEvt, recalc(1), !1);  // 监听手机横竖屏事件
        doc.addEventListener("DOMContentLoaded", recalc(2), !1); // 在形成完整的DOM树之后就会触发,不理会图像、JS文件、css文件是否已经下载完毕,用户可以早点与页面进行交互 ie9+支持,window.load()则是全部加载完毕触发
        recalc(3)   // 进入页面调用一次
      }
    }(document, window);
var a = '';
a && document.write('abc')  // 等同于 if(a){...}
  if(a){
  document.write('abc')
  }

 js滚动监听

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<style>
  .a {
    width: 200px;
    height: 300px;
    border: 1px solid green;
  }

  .active {
    background: red;
  }
</style>
<nav>
  <ul style="position: fixed;top:10px;left:20px;">
    <li><a href="#About">About</a></li>
    <li><a href="#Skill">Skill</a></li>
    <li><a href="#Experience">Experience</a></li>
    <li><a href="#More">More</a></li>
    <li><a href="#Contact">Contact</a></li>
  </ul>
</nav>
<div style="height:100px;"></div>
<div class="a" id="About" style="height: 200px;">
  about
</div>
<div class="a" id="Skill" style="height: 300px;">
  skill
</div>
<div class="a" id="Experience" style="height: 400px;">
  expre
</div>
<div class="a" id="More" style="height:500px;">
  more
</div>
<div class="a" id="Contact" style="height:600px;">
  concact
</div>
<div style="height:1000px;">00</div>
<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script>
  var a = $('a[href]', 'nav');
  a.click(function () {

    var href = $(this).attr('href');
    var o = $(href).offset();
    $(window).scrollTop(o.top, 1000); //增加个动画效果
  });
  var b = $(".a")
  $(window).on('scroll', function () {
    b.removeClass('active');
    for (var i = 0; i < b.length; i++) {
      var $b = b.eq(i), st = $(window).scrollTop();
      var top = $b.offset().top;
      if (st >= top && st <= $b.height() + top) //  top >= st >= top + height
      {
        console.log(i);
        $b.addClass('active'); //此处已经获得了哪个a
        break;
      }
    }

  });
</script>
</body>
</html>
View Code

 

转载于:https://www.cnblogs.com/gyz418/p/7372702.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值