DIV CSS 佈局教程網

JavaScript 實用小技巧彙整(值得收藏)
編輯:關於JavaScript     

直接上乾貨!以下彙整一系列常見又實用的 JavaScript 與 jQuery 小技巧,涵蓋字串處理、設備判斷、動畫效果、表單操作等日常情境。

字串截斷(中文算兩個字元)

var subString = function(str, len) {
  var newLength = 0, newStr = "";
  var chineseRegex = /[^\x00-\xff]/g;
  var singleChar = "";
  var strLength = str.replace(chineseRegex, "**").length;
  for (var i = 0; i < strLength; i++) {
    singleChar = str.charAt(i).toString();
    if (singleChar.match(chineseRegex) != null) { newLength += 2; }
    else { newLength++; }
    if (newLength > len) { break; }
    newStr += singleChar;
  }
  if (strLength > len) { newStr += "..."; }
  return newStr;
};

依設備載入不同樣式

if (/(iPad|iPod|iOS)/i.test(navigator.userAgent)) {
  setActiveStyleSheet("pad.css");
} else if (/(Android)/i.test(navigator.userAgent)) {
  setActiveStyleSheet("common.css");
}

回到頁面頂部動畫

$('a.top').click(function(e) {
  e.preventDefault();
  $(document.body).animate({ scrollTop: 0 }, 800);
});

檢查圖片是否載入完成

$('img').load(function() {
  console.log('image load successful');
});

修復損壞的圖片

$('img').on('error', function() {
  $(this).prop('src', 'img/broken.png');
});

滑鼠移入切換 class

$('.btn').hover(function() {
  $(this).toggleClass('hover');
});

停用表單欄位

$('input[type="submit"]').prop('disabled', true);
$('input[type="submit"]').prop('disabled', false);

阻止連結跳轉

$('a.no-link').click(function(e) {
  e.preventDefault();
});

淡入淡出/滑動開關

$('.btn').click(function() {
  $('.element').fadeToggle('slow');
});
$('.btn').click(function() {
  $('.element').slideToggle('slow');
});

簡單手風琴效果

$('#accordion').find('.content').hide();
$('#accordion').find('.accordion-header').click(function() {
  var next = $(this).next();
  next.slideToggle('fast');
  $('.content').not(next).slideUp('fast');
  return false;
});

讓兩個 div 等高

var $columns = $('.column');
var height = 0;
$columns.each(function() {
  if ($(this).height() > height) { height = $(this).height(); }
});
$columns.height(height);

站外連結在新分頁開啟

$('a[href^="http"]').attr('target', '_blank');
$('a[href^="' + window.location.origin + '"]').attr('target', '_self');

Ajax 全域錯誤處理

$(document).ajaxError(function(e, xhr, settings, error) {
  console.log(error);
});

插件鏈式調用

$('#elem').show().html('bla').otherStuff();

全選/全不選

$('#checkAll').click(function() {
  var bischecked = $('#checkAll').is(':checked');
  var fruit = $('input[name="check"]');
  bischecked ? fruit.attr('checked', true) : fruit.attr('checked', false);
});

以上就是這份實用 JavaScript/jQuery 小技巧彙整,日常開發中都能派上用場,希望對你有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved