前端常用的JavaScript和jquery代码片段
记录一下自己写前端整理下来的一些笔记。
1、数组去重
// 数组排重 function getFilterArray (array) { const res = []; const json = {}; for (let i = 0; i < array.length; i++){ const _self = array[i]; if(!json[_self]){ res.push(_self); json[_self] = 1; } } return res; }
2、双向绑定(面试常考)
Object.defineProperty() //方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性, 并返回这个对象。 <div id="app"> <input type="text" id="txt"> <p id="show-txt"></p> </div> <script> var obj = {} Object.defineProperty(obj, 'txt', { get: function () { return obj }, set: function (newValue) { document.getElementById('txt').value = newValue document.getElementById('show-txt').innerHTML = newValue } }) document.addEventListener('keyup', function (e) { obj.txt = e.target.value }) </script>
3、平稳滑动到页面顶部
$("a[href='#top']").click(function() { $("html, body").animate({ scrollTop: 0 }, "slow"); return false; }); var handleGoTop = function () { var offset = 300; var duration = 500; if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) { // ios supported $(window).bind("touchend touchcancel touchleave", function(e){ if ($(this).scrollTop() > offset) { $('.scroll-to-top').fadeIn(duration); } else { $('.scroll-to-top').fadeOut(duration); } }); } else { // general $(window).scroll(function() { if ($(this).scrollTop() > offset) { $('.scroll-to-top').fadeIn(duration); } else { $('.scroll-to-top').fadeOut(duration); } }); } $('.scroll-to-top').click(function(e) { e.preventDefault(); $('html, body').animate({scrollTop: 0}, duration); return false; }); };
4、固定在顶部
$(function(){ var $win = $(window) var $nav = $('.mytoolbar'); var navTop = $('.mytoolbar').length && $('.mytoolbar').offset().top; var isFixed=0; processScroll() $win.on('scroll', processScroll) function processScroll() { var i, scrollTop = $win.scrollTop() if (scrollTop >= navTop && !isFixed) { isFixed = 1 $nav.addClass('subnav-fixed') } else if (scrollTop <= navTop && isFixed) { isFixed = 0 $nav.removeClass('subnav-fixed') } }
5、自动定位并修复损坏图片(如果你的站点比较大而且已经在线运行了好多年,你或多或少会遇到界面上某个地方有损坏的图片。这个有用的函数能够帮助检测损坏图片并用你中意的图片替换它,并会将此问题通知给访客。)
$('img').error(function(){ $(this).attr('src', 'img/broken.png'); });
6、在文本或密码输入时禁止空格键
$('input.nospace').keydown(function(e) { if (e.keyCode == 32) { return false; } });
7、在图片上停留时逐渐增强或减弱的透明效果
$(document).ready(function(){ $(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads $(".thumbs img").hover(function(){ $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover },function(){ $(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout }); });
8、检测复制、粘贴和剪切的操作
$("#textA").bind('copy', function() { $('span').text('copy behaviour detected!') }); $("#textA").bind('paste', function() { $('span').text('paste behaviour detected!') }); $("#textA").bind('cut', function() { $('span').text('cut behaviour detected!') });
9、随机生成字符串
//生成随机字符串 function GenerateRanCode(length) { length = length || 8; var source = "abcdefghzklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var s = ""; for (var i = 0; i < length; i++) { s += source.charAt(Math.ceil(Math.random() * 1000) % source.length); } return s; }
10、设置复选框(单选/全选)
function SelectAllCheckBoxOrNot(chAllId, TagName) { var allValue = $("#" + chAllId).prop("checked"); $("#" + TagName + " input[name='test']").prop("checked", allValue); };
11、点击空白处隐藏菜单
(function ($) { /*点击空白处隐藏菜单*/ $.fn.autoHide = function () { var ele = $(this); $(document).on('click', function (e) { if(ele.is(':visible') && (!$(e.target)[0].isEqualNode(ele[0]) && ele.has(e.target).length === 0)){ ele.hide(); } }); return this; } })(jQuery);
12、时间格式
//时间格式 Date.prototype.format = function (format) { var date = { "M+": this.getMonth() + 1, "d+": this.getDate(), "h+": this.getHours(), "m+": this.getMinutes(), "s+": this.getSeconds(), "q+": Math.floor((this.getMonth() + 3) / 3), "S+": this.getMilliseconds() }; if (/(y+)/i.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length)); } for (var k in date) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length)); } } return format; };
13、获取一周的开始日期和结束日期
function getStartAndEndOfWeek(flag) { var result; var now = new Date(); //当前日期 var nowDayOfWeek = now.getDay(); //今天本周的第几天 var nowDay = now.getDate(); //当前日 var nowMonth = now.getMonth(); //当前月 var nowYear = now.getYear(); //当前年 nowYear += (nowYear < 2000) ? 1900 : 0; if (flag == 1){ //获得本周的开端日期 var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1); result = weekStartDate.format('yyyy-MM-dd'); }else if(flag == 2){ //获得本周的停止日期 var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek) + 1); result = weekEndDate.format('yyyy-MM-dd'); } return result; };