JS题 应用

  • 实现一个动画函数,无需考虑透明度
    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)
    }
    
  • 节流函数的实现(类似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索引

    • 这是第一条
    • 这是第二条
    • 这是第三条
    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赋值给内部函数
    for (var i = 0; i < lis.length; i++) {
        lis[i].onclick = (function(arg) {
            return function() {
                console.log(arg);
            }
        })(i)
    }
    
  • 获取元素聚页面左边、顶部的距离

    // 一直向上获取目标元素的父定位元素。注意不能用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 }
    }
    
  • 常规URL的正则匹配

    //开始 + 可选的http或https协议名 + 一个以上的(一个以上的字母或数字或'-' + '.') + 一个以上的字母或数字 + 一个以上的('/' + 一个以上的非空格字符 ) + 结尾
    /^(http:\/\/|https:\/\/)?([\w-]+\.)+[\w-]+(\/\S+)+$/
    

你可能感兴趣的:(JS题 应用)