前端技巧——js篇

前端技巧——js篇

复制操作

copy () {
  let url = this.code;
  let oInput = document.createElement('input');
  oInput.value = url;
  document.body.appendChild(oInput);
  oInput.select();  // 选择对象
  console.log(oINput.value);
  document.execCommand('Cooy'); //  执行浏览器复制命令
  alert('复制成功');
  oInput.remove();
}

出生日期转年龄【正则】

function getAge(str) {
  var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
  r === null ? return false : '' ;
  var d = new Date(r[1], r[3]-1, r[4]);
  if (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate == r[4]) {
    var Y = new Date().getFullYear();
    return (Y - r[1]);
  }
  return '输入有误,请检查格式';
}

随即打乱顺序

var arr = [1,2,3,4,5,6,7,8,9,0];
arr.sort(() => {
  return (0.5 - Math.random());
})

截取url参数

function getParams () {
  var obj = {};
  var url = window.location.search; // 截取'?'及之后的字符串
  var str = url.string(1, url.length);  // 删除'?'
  var arr = str.split('&'); // 分割数组
  for (var i = 0; i < arr.length; i ++) {
    obj[arr[i].split('=')[0]] = unescape(arr[i].split('=')[1]);
  }
}

字体自适应

// 根元素
var win = window,
doc = document;
function setFontSize() {
  var winWidth = $(window).width();
  // 设计稿比如为750  可自定义
  var size = (winWidth / 750) * 100;
  doc.documentElement.style.fontSize = (size < 100 ? size : 100) + 'px';
};
// 页面初始化
setTimeout(function() {
  setFontSize();
}, 100);

随机数

var n = parseInt(10 * Math.random()); // 0~10之间随机整数
console.log(n);

n个元素圆形布局

<style>
.container{
  position: relative;
  width: 600px;
  height: 600px;
  margin: 0 auto;
  border: 1px solid #f00;
}
.box{
  position: absolute;
  width: 50px;
  height: 50px;
  background: #eee;
  transform: translate(-50%, -50%);
}
</style>

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

<script>
  // 注,此方法的box可为n个
  $(function () {
    // 中心点横坐标
    var ow = $('.container').width() / 2;
    // 中心点纵坐标
    var ot = $('.container').height() / 2;
    // 起始角度
    var start = 0;
    // 半径
    var radius = 300;
    // 每一个box对应的角度
    var avd = 360 / $('.box').length;
    // 每一个box对应的弧度
    var ahd = avd * Math.PI / 180;
    // 设置每一个元素的位置
    $(.box).each(function (index, element) {
      $(this).css({
        'left': Math.sin(ahd * index) * radius + ow,
        'top': Math.cos(ahd * index) * radius + oh
      })
    })
  })
</script>

桌面弹窗【原生】

// 判断浏览器是否支持“WebNotifications API”
function justify_notifyAPI () {
  if (window.Notification) {
    // 支持
    console.log('支持:WebNotifications API');
  } else {
    console.log('不支持:WebNotifications API');
  }
}
// 浏览器是否支持弹出实例
function justify_showMsg () {
  if (window.Notification && Notification.permission !== 'undefined') {
    Notification.requestPermission(function (status) {
      if (status === 'granted') {
        var n = New Notification('收到消息:-O', {
          body: '这是通知内容',
          icon: 'imgUrl'
        })
      } else {
        var n = new Notification('baby, i'll leave u');
      }
    })
  }
}
// 实例展示弹出内容
function otification_construct () {
  var notification = new Notification('收到新邮件', {
    body: '您有一封来自马来西亚??的新邮件',
    dir: 'auto',
    lang: 'zh-CN',
    tag: 'a1',
    icon: 'imgUrl'
  });
  console.log(notification.title);  // 收到新邮件
  console.log(notification.body);   //  您有一封...
}
// Notifications API的相关事件
function otification_event () {
  var MM = new Notification('新消息', {
    body: '一条来自越南??的留言',
    icon: 'imgUrl'
  });
  // 查看信息
  MM.onshow = function () {
    window.open('index.html');  // 打开首页
    MM.close(); // 关闭桌面弹窗
  };
  //  报错处理
  MM.onerror = function () {
    console.log('Notification have be click');
    MM.close();
  }
}

jQuery阻止重复加载

$('#btn').off('click').on('click', function () {
  // ...
})
jQuery平缓滑动至顶部

// 点击返回顶部按钮平缓滑到顶部
$('#top').on('click',function () {
  $('html, body').animate(
    {scrollTop: 0,},
    {duration: 500,easing: 'swing'}
    );
    return false
})

// 绑定页面滚动事件
$(window).bind('scroll', function () {
  var t = $(this).scrollTop();
  if(t > 100) {
    $('#top').fadeIn(1000);
  } else {
    $('#top').fadeOut(1000);
  }
})

jQuery平缓滑倒自定义位置

$('.box').on('click', '.link', function () {
  var linkAdd = $(this).attr('data');
  $('html, body').animate(
    {scrollTop: $(`#${linkAdd}`).offset().top - 71 + 'px'},
    {duration: 500, easing: 'swing'};
  )
  return false
})

全屏/取消全屏【原生】

<div style="margin:0;height: 100vh;width:100vw; background:#900;overflow: hidden;">
    <button id="btn">js控制页面的全屏展示和退出全屏显示</button>
    <div id="content" style="width: 100%;height: 100%;background-color: #00ee00;">
        <div>这个div的父级下是可以全屏显示的内容</div>
        <button onclick="exitFull()">js控制页面的退出全屏显示</button>
    </div>
</div>

<script language="JavaScript">
document.getElementById("btn").onclick=function(){
    var elem = document.getElementById("content");
    requestFullScreen(elem);// 某个页面元素
    //requestFullScreen(document.documentElement);// 整个网页
};

function requestFullScreen(element) {
    // 判断各种浏览器,找到正确的方法
    var requestMethod = element.requestFullScreen || //W3C
            element.webkitRequestFullScreen ||    //Chrome等
            element.mozRequestFullScreen || //FireFox
            element.msRequestFullScreen; //IE11
    if (requestMethod) {
        requestMethod.call(element);
    }
    else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
            wscript.SendKeys("{F11}");
        }
    }
}

//退出全屏 判断浏览器种类
function exitFull() {
    // 判断各种浏览器,找到正确的方法
    var exitMethod = document.exitFullscreen || //W3C
            document.mozCancelFullScreen ||    //Chrome等
            document.webkitExitFullscreen || //FireFox
            document.webkitExitFullscreen; //IE11
    if (exitMethod) {
        exitMethod.call(document);
    }
    else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
            wscript.SendKeys("{F11}");
        }
    }
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值