直接上乾貨!以下彙整一系列常見又實用的 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');
});
$('.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;
});
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');
$(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 小技巧彙整,日常開發中都能派上用場,希望對你有所幫助。