当前位置: 代码迷 >> 综合 >> 简单的鼠标拖拽(1)颜色渐变
  详细解决方案

简单的鼠标拖拽(1)颜色渐变

热度:29   发布时间:2023-10-27 11:33:21.0

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>鼠标拖拽</title>
        <style type="text/css">
            *{
                margin: 0;
                padding: 0;
            }
            #box{
                width: 400px;
                height: 50px;
                background: gray;
                position: relative;
            }
            #box1{
                width: 50px;
                height: 50px;
                background: red;
                position: absolute;
                left: 0;
                top: 0;
            }
            #box2{
                width: 400px;
                height: 400px;
                background: green;
                opacity: 0;
            }
        </style>
    </head>
    <body>
        <div id="box">
            <div id="box1">
                
            </div>
            
        </div>
        <div id="box2">
                
        </div>
        <script type="text/javascript">
            var box = document.getElementById('box');
            var box1 = document.getElementById('box1');
            var box2 = document.getElementById('box2');
            var w = box.offsetWidth - box1.offsetWidth;
            var h = box.offsetHeight - box1.offsetHeight;
            box1.onmousedown = function(){
                var selfX = event.clientX - this.offsetLeft;
                var selfY = event.clientY - this.offsetTop;
                document.onmousemove = function(){
                    var newLeft = event.clientX - selfX;
                    var newTop = event.clientY - selfY;
                    if (newLeft<=0){
                        newLeft = 0;
                    }else if(newLeft>= w){
                        newLeft =w + "px";        
                    }
                    box1.style.left = newLeft +'px'
                    box2.style.opacity = newLeft/w;
                }
                document.onmouseup = function(){
                    document.onmousemove = null;
                    document.onmouseup = null;
                }
            }
        </script>
    </body>
</html>

  相关解决方案