Javascript的小demo(2):放大功能

放大功能

运用的是
鼠标事件 onmousedown() , onmousemove(),onmouseup()
计算鼠标距离视口左边 e.clientX
计算元素距离视口左边 box.offsetLeft
获取元素的宽度 box.clientWidth /box.offsetWidth

<head>
    <style>
            .box1{
            height:400px;
            width: 400px;
            background: pink;
            position: absolute;
            top: 100px;
            left: 100px;
        }
        .box2{
            height:100px;
            width: 100px;
            background: palevioletred;
            position: absolute;
            top: 0;
            left: 0;
        }
        .box3{
            height:15px;
            width: 15px;
            background: purple;
            position: absolute;
            right: 0;
            bottom: 0;
            border-radius: 50%;
        }

    </style>
</head>
<body>
    <div class="box1" id="box1">
        <div class="box2" id="box2">
            <div class="box3" id="box3"></div>
        </div>
    </div>


<script>
    var box1 = document.querySelector(".box1");
    var box2 = document.querySelector(".box2");
    var box3 = document.querySelector(".box3");

    box3.onmousedown = function(e){
        var startX = e.clientX;
        var startY = e.clientY;

        var width = box2.clientWidth;
        var height = box2.clientHeight;
 

        document.onmousemove = function(e){
            var endX = e.clientX;
            var endY = e.clientY;
   
            var  resX = width + endX - startX;
            var  resY =  height + endX - startX;

            if(resX < 30){
                resX = 30;
            }else if(resX > box1.clientWidth - box2.offsetLeft){
                resX = box1.clientWidth - box2.offsetLeft ;
            }

            if(resY < 30){
                resY = 30;
            }else if(resY > box1.clientHeight - box2.offsetTop ){
                resY = box1.clientHeight - box2.offsetTop ;
            }

            box2.style.width = resX +"px";
            box2.style.height = resY+"px";
        }
    }

    document.onmouseup = function(){
        document.onmousemove = null;
    }
</script>
</body>

你可能感兴趣的:(前端)