前端常用的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 > <input type="text" > <p ></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') } }