前端設計師們最常用的JS代碼匯總_javascript技巧

來源:互聯網
上載者:User

逛社區時看到的文章,我修改調整了內容,如果大家覺得也有協助 可以收藏下~

HTML5 DOM 選取器

// querySelector() 返回匹配到的第一個元素var item = document.querySelector('.item');console.log(item);// querySelectorAll() 返回匹配到的所有元素,是一個nodeList集合var items = document.querySelectorAll('.item');console.log(items[0]);

阻止預設行為

// 原生jsdocument.getElementById('btn').addEventListener('click', function (event) {  event = event || window.event;  if (event.preventDefault){    // w3c方法 阻止預設行為    event.preventDefault();  } else{    // ie 阻止預設行為    event.returnValue = false;  }}, false);// jQuery$('#btn').on('click', function (event) {  event.preventDefault();});

阻止冒泡

// 原生jsdocument.getElementById('btn').addEventListener('click', function (event) {  event = event || window.event;  if (event.stopPropagation){    // w3c方法 阻止冒泡    event.stopPropagation();  } else{    // ie 阻止冒泡    event.cancelBubble = true;  }}, false);// jQuery$('#btn').on('click', function (event) {  event.stopPropagation();});

滑鼠滾輪事件

$('#content').on("mousewheel DOMMouseScroll", function (event) {   // chrome & ie || // firefox  var delta = (event.originalEvent.wheelDelta && (event.originalEvent.wheelDelta > 0 ? 1 : -1)) || (event.originalEvent.detail && (event.originalEvent.detail > 0 ? -1 : 1));     if (delta > 0) {     // 向上滾動    console.log('mousewheel top');  } else if (delta < 0) {    // 向下滾動    console.log('mousewheel bottom');  } });

檢測瀏覽器是否支援svg

function isSupportSVG() {   var SVG_NS = 'http://www.w3.org/2000/svg';  return !!document.createElementNS &&!!document.createElementNS(SVG_NS, 'svg').createSVGRect; } // 測試console.log(isSupportSVG());

檢測瀏覽器是否支援canvas

function isSupportCanvas() {  if(document.createElement('canvas').getContext){    return true;  }else{    return false;  }}// 測試,開啟Google瀏覽器控制台查看結果console.log(isSupportCanvas());

檢測是否是微信瀏覽器

function isWeiXinClient() {  var ua = navigator.userAgent.toLowerCase();   if (ua.match(/MicroMessenger/i)=="micromessenger") {     return true;   } else {     return false;   }}// 測試alert(isWeiXinClient());

jQuery 擷取滑鼠在圖片上的座標

$('#myImage').click(function(event){  //擷取滑鼠在圖片上的座標   console.log('X:' + event.offsetX+'\n Y:' + event.offsetY);     //擷取元素相對於頁面的座標   console.log('X:'+$(this).offset().left+'\n Y:'+$(this).offset().top);});

驗證碼倒計時代碼

<!-- dom --><input id="send" type="button" value="發送驗證碼">
// 原生js版本var times = 60, // 臨時設為60秒  timer = null;      document.getElementById('send').onclick = function () {  // 計時開始  timer = setInterval(function () {    times--;        if (times <= 0) {      send.value = '發送驗證碼';      clearInterval(timer);      send.disabled = false;      times = 60;    } else {      send.value = times + '秒後重試';      send.disabled = true;    }  }, 1000);}// jQuery版本var times = 60,  timer = null;$('#send').on('click', function () {  var $this = $(this);    // 計時開始  timer = setInterval(function () {    times--;        if (times <= 0) {      $this.val('發送驗證碼');      clearInterval(timer);      $this.attr('disabled', false);      times = 60;    } else {      $this.val(times + '秒後重試');      $this.attr('disabled', true);    }  }, 1000);});

常用的一些Regex

//匹配字母、數字、中文字元 /^([A-Za-z0-9]|[\u4e00-\u9fa5])*$/ //驗證郵箱 /^\w+@([0-9a-zA-Z]+[.])+[a-z]{2,4}$/ //驗證手機號 /^1[3|5|8|7]\d{9}$/ //驗證URL /^http:\/\/.+\.///驗證社會安全號碼碼 /(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/ //匹配中文字元的Regex /[\u4e00-\u9fa5]/ //匹配雙位元組字元(包括漢字在內) /[^\x00-\xff]/

js時間戳記、毫秒格式化

function formatDate(now) {   var y = now.getFullYear();  var m = now.getMonth() + 1; // 注意js裡的月要加1   var d = now.getDate();  var h = now.getHours();   var m = now.getMinutes();   var s = now.getSeconds();    return y + "-" + m + "-" + d + " " + h + ":" + m + ":" + s; } var nowDate = new Date(2016, 5, 13, 19, 18, 30, 20);console.log(nowDate.getTime()); // 獲得當前毫秒數: 1465816710020console.log(formatDate(nowDate));

js限定字元數(注意:一個漢字算2個字元)

<input id="txt" type="text">
//字串截取function getByteVal(val, max) {  var returnValue = '';  var byteValLen = 0;  for (var i = 0; i < val.length; i++) {    if (val[i].match(/[^\x00-\xff]/ig) != null) byteValLen += 2; else byteValLen += 1;    if (byteValLen > max) break;    returnValue += val[i];  }  return returnValue;}$('#txt').on('keyup', function () {  var val = this.value;  if (val.replace(/[^\x00-\xff]/g, "**").length > 14) {    this.value = getByteVal(val, 14);  }});

js判斷是否移動端及瀏覽器核心

var browser = {   versions: function() {     var u = navigator.userAgent;     return {       trident: u.indexOf('Trident') > -1, //IE核心       presto: u.indexOf('Presto') > -1, //opera核心       webKit: u.indexOf('AppleWebKit') > -1, //蘋果、Google核心       gecko: u.indexOf('Firefox') > -1, //Firefox核心Gecko       mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否為移動終端       ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios       android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android       iPhone: u.indexOf('iPhone') > -1 , //iPhone       iPad: u.indexOf('iPad') > -1, //iPad       webApp: u.indexOf('Safari') > -1 //Safari     };   }} if (browser.versions.mobile() || browser.versions.ios() || browser.versions.android() || browser.versions.iPhone() || browser.versions.iPad()) {   alert('移動端'); }

之前我用過一個檢測用戶端的庫 覺得挺好用的,也推薦給大家 叫 device.js,大家可以 Googel 或 百度
GItHub倉庫地址:https://github.com/matthewhudson/device.js

getBoundingClientRect() 擷取元素位置

//它返回一個對象,其中包含了left、right、top、bottom四個屬性var myDiv = document.getElementById('myDiv');var x = myDiv.getBoundingClientRect().left; var y = myDiv.getBoundingClientRect().top; // 相當於jquery的: $(this).offset().left、$(this).offset().top // js的:this.offsetLeft、this.offsetTop

HTML5全屏

function fullscreen(element) {  if (element.requestFullscreen) {    element.requestFullscreen();  } else if (element.mozRequestFullScreen) {    element.mozRequestFullScreen();  } else if (element.webkitRequestFullscreen) {    element.webkitRequestFullscreen();  } else if (element.msRequestFullscreen) {    element.msRequestFullscreen();  }}fullscreen(document.documentElement);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.