总结

作者: 郭先生_515 | 来源:发表于2020-10-30 17:07 被阅读0次
  1. 自定义事件
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>自定义事件</title>
</head>
<body>
    <button id="btn">按钮</button>
</body>
<script>
    let oBtn = document.getElementById('btn')
    oBtn.onclick = function(event) {
        let ev = event || window.event;
        let eve = new Event('test');
        oBtn.addEventListener('test', function() {
            console.log('test capture');
        })
        setTimeout(function() {
            oBtn.dispatchEvent(eve)
        }, 1000);
    }
</script>
</html>
  1. 拖拽
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>拖拽</title>
    <style>
        #div1 {
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
        }
    </style>
</head>
<body>
    <div id="div1"></div>
</body>
<script>
    let oDiv = document.getElementById('div1');
    oDiv.onmousedown = function(event) {
        let ev = event || window.event;
        let x1 = ev.clientX - oDiv.offsetLeft;
        let y1 = ev.clientY - oDiv.offsetTop;
        oDiv.onmousemove = function(event) {
            let ev = event || window.event;
            oDiv.style.left = ev.clientX - x1 + 'px';
            oDiv.style.top = ev.clientY - y1 + 'px';
            document.onmouseup = function() {
                oDiv.onmousemove = null;
                oDiv.onmouseup = null;
            }
        }
    }
</script>
</html>
  1. promise
function test(resolve, reject) {
    let random = Math.random()*2
    setTimeout(function(){
        if (random<1) {
            console.log('success');
            resolve('200 OK')
        }else{
            console.log('error')
            reject('随机数为'+random+'>1')
        }
    }, 1000)
}

let p1 = new Promise(test);
let p2 = p1.then(function(res) {
    console.log('成功:'+res)
})
let p3 = p2.catch(function(err) {
    console.log('失败:'+err)
})

相关文章

网友评论

      本文标题:总结

      本文链接:https://www.haomeiwen.com/subject/sgjroqtx.html