碰撞

作者: Wo信你个鬼 | 来源:发表于2019-03-12 15:18 被阅读0次
    pd.png
    <!DOCTYPE html>
    <html>
    
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                #p1 {
                    width: 100px;
                    height: 100px;
                    background: green;
                    position: absolute;
                }
                
                #p2 {
                    width: 100px;
                    height: 100px;
                    background: yellow;
                    position: absolute;
                    left: 300px;
                    top: 200px;
                    z-index: -1;
                }
            </style>
        </head>
    
        <body>
            <p id="p1"></p>
    
            <p id="p2"></p>
            <script>
                window.onload = function() {
    
                    var op = document.getElementById('p1');
    
                    var op2 = document.getElementById('p2');
    
                    var disX = 0;
    
                    var disY = 0;
    
                    op.onmousedown = function(ev) {
    
                        var ev = ev || window.event;
    
                        disX = ev.clientX - op.offsetLeft;
    
                        disY = ev.clientY - op.offsetTop;
    
                        document.onmousemove = function(ev) {
    
                            var ev = ev || window.event;
    
                            var t1 = op.offsetTop;
    
                            var l1 = op.offsetLeft;
    
                            var r1 = op.offsetLeft + op.offsetWidth;
    
                            var b1 = op.offsetTop + op.offsetHeight;
    
                            var t2 = op2.offsetTop;
    
                            var l2 = op2.offsetLeft;
    
                            var r2 = op2.offsetLeft + op2.offsetWidth;
    
                            var b2 = op2.offsetTop + op2.offsetHeight;
    
                            if(b1 < t2 || l1 > r2 || t1 > b2 || r1 < l2) { // 表示没碰上
    
                            } else {
    
                                op2.style.background = 'blue';
    
                            }
    
                            op.style.left = ev.clientX - disX + 'px';
    
                            op.style.top = ev.clientY - disY + 'px';
    
                        }
    
                        document.onmouseup = function() {
    
                            document.onmousemove = null;
    
                            document.onmouseup = null;
    
                        }
    
                        return false;
    
                    }
    
                }
            </script>
        </body>
    
    </html>
    

    相关文章

      网友评论

          本文标题:碰撞

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