原生javascript实现鼠标在窗口按下拖动,元素放大效果。

原生javascript实现鼠标在窗口按下拖动,元素放大效果。_第1张图片

代码如下:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>鼠标按下拖动,元素放大效果title>
    <style>
        *{margin:0;padding:0;user-select:none;height:100%;overflow:hidden;}
        #od{height:400px;width:400px;margin:100px auto;background:red;transition:all .4s ease-out;}
    style>
head>
<body>
    <div class="ob" id="od">
        1
    div>
    <script>
        function $(selector){
            return document.querySelector(selector);
        }

        var body = $("body");
        var flag = false;
        var mouseX,mouseY;
        var bodyWidth,bodyHeight;

        //窗口宽度
        if (window.innerWidth){
            bodyWidth = window.innerWidth; 
        }else if((document.body) && (document.body.clientWidth)){ 
            bodyWidth = document.body.clientWidth; 
        }

        //窗口高度
        if (window.innerHeight){
            bodyHeight = window.innerHeight; 
        }else if((document.body) && (document.body.clientHeight)){ 
            bodyHeight = document.body.clientHeight; 
        }

        //注意必须监听文档事件,不能监听body,因为如果监听body的话当鼠标按下离开窗口,(比如移动到底部任务栏时会出现bug)     
        //鼠标按下后的效果
        document.onmousedown = function(e){
            flag = true;
            e = e || window.event;
            mouseX = e.pageX;
            mouseY = e.pageY;
            console.log(mouseX);
        };

        //鼠标松开后的效果
        document.onmouseup = function(e){
            flag = false;
            body.style.webkitTransform = "scale(1)";
            mouseX = e.pageX;
            mouseX = e.pageY;
            console.log(1111111);

        };

        //鼠标移动的效果
        document.onmousemove = function(e){
            console.log("a");
            e = e || window.event;
            var a_mouseX = e.pageX;
            var a_mouseY = e.pageY;
            var scaleNumx = (a_mouseX - mouseX)/bodyWidth + 1;  //X放大倍数
            var scaleNumy = (a_mouseY - mouseY)/bodyHeight + 1; //Y放大倍数
            console.log(scaleNumx+"--"+scaleNumy)

            //如果鼠标按下了
            if(flag){
                body.style.webkitTransform = "scale(" + scaleNumx + "," + scaleNumy + ")";
            }else{
                return false;
            }

        }
    script>
body>
html>

注意必须监听文档事件,不能监听body,因为如果监听body的话当鼠标按下离开窗口,(比如移动到底部任务栏时会出现bug)详情可以看下为什么会这样。
https://segmentfault.com/q/1010000004973341

你可能感兴趣的:(web前端,javascript,CSS3,HTML5)