- 實現(xiàn)一個動畫函數(shù),無需考慮透明度
function animate(ele, tarStyle, tarValue) { var fullStyleValue = getComputedStyle(ele)[tarStyle] var currentValue = parseFloat(fullStyleValue) var animationId = setInterval(function() { if (currentValue !== tarValue) { currentValue += Math.ceil((tarValue - currentValue) / 10) } else { clearInterval(animationId) } ele.style[tarStyle] = currentValue + 'px' }, 20) }
- 節(jié)流函數(shù)的實現(xiàn)(類似Vue1的debounce)
function debounce(fn, delay) { var timer = null return function () { var context = this var args = arguments clearTimeout(timer) timer = setTimeout(function () { fn.apply(context, args) }, delay) } }
-
點擊li時alert索引
<ul id="container"> <li>這是第一條</li> <li>這是第二條</li> <li>這是第三條</li> </ul>
var lis = document.getElementsByTagName('li') // 1 - 事件代理 document.getElementById('container').addEventListener('click', function(e) { if (e.target.nodeName === 'LI') { console.log(Array.prototype.indexOf.call(lis, e.target)); } }) // 2 - 分別加onclick Array.prototype.forEach.call(lis, function(item, index) { item.onclick = function() { console.log(index); } }) // 3 - 單個加onclick,用let for (let i = 0; i < lis.length; i++) { lis[i].onclick = function() { console.log(i); } } // 4 - 單個加onclick,把i賦值給內(nèi)部函數(shù) for (var i = 0; i < lis.length; i++) { lis[i].onclick = (function(arg) { return function() { console.log(arg); } })(i) }
-
獲取元素聚頁面左邊、頂部的距離
// 一直向上獲取目標(biāo)元素的父定位元素。注意不能用getBoundingClientRect()方法,那個返回的是距離視口的距離 function offset(t) { var top = t.offsetTop var left = t.offsetLeft var posParent = t.offsetParent while (posParent !== null) { top += posParent.offsetTop left += posParent.offsetLeft posParent = posParent.offsetParent } return { top: top, left: left } }
-
常規(guī)URL的正則匹配
//開始 + 可選的http或https協(xié)議名 + 一個以上的(一個以上的字母或數(shù)字或'-' + '.') + 一個以上的字母或數(shù)字 + 一個以上的('/' + 一個以上的非空格字符 ) + 結(jié)尾 /^(http:\/\/|https:\/\/)?([\w-]+\.)+[\w-]+(\/\S+)+$/