温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript如何实现鼠标移动事件

发布时间:2022-08-23 16:34:20 来源:亿速云 阅读:137 作者:iii 栏目:开发技术

这篇文章主要介绍了JavaScript如何实现鼠标移动事件的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇JavaScript如何实现鼠标移动事件文章都会有所收获,下面我们一起来看看吧。

实现功能

鼠标点击时可以在画板上画画
如果鼠标双击那么停止
移动进画板颜色改变移除时颜色改变

<!DOCTYPE html>
<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>Document</title>
  </head>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    .drawbox {
      width: 1100px;
      height: 600px;
      background-color: skyblue;
      position: relative;
    }
  </style>
  <body>
    <div class="drawbox"></div>
    <script>
      /* 
        1.鼠标点击时可以在画板上画画
        如果鼠标双击那么停止
        移动进画板颜色改变移除时颜色改变
        */
      var darwbox = document.querySelector("div");
      darwbox.onmouseenter = function() {
        darwbox.style.backgroundColor = "red";
      };
      darwbox.onmouseleave = function() {
        darwbox.style.backgroundColor = "skyblue";
      };
      var istrue = false;
      darwbox.onmousedown = function(e) {
        istrue = true;
      };
      darwbox.onmousemove = function(e) {
        if (istrue == true) {
          var x = e.pageX;
          var y = e.pageY;
          var circle = document.createElement("div");
          circle.style.width = "10px";
          circle.style.height = "10px";
          circle.style.backgroundColor = "#fff";
          circle.style.position = "absolute";
          circle.style.left = x - 5 + "px";
          circle.style.top = y - 5 + "px";
          circle.style.borderRadius = "50%";
         
          darwbox.appendChild(circle);
        }
      };
      darwbox.onmouseup = function(e) {
        istrue = false;
      };
    </script>
  </body>
</html>

效果图:

JavaScript如何实现鼠标移动事件

关于“JavaScript如何实现鼠标移动事件”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“JavaScript如何实现鼠标移动事件”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI