DOM& 鼠标按下、移动与松开事件小练习

195 阅读1分钟

##文档对象模型 DOM##

  1. document.getElementByClassName() 与 document.getElementsByClassName() 区别,你知道吗? 前者只单个对象,后者是数组 例:var demo = document.getElementsByClassName("app"), demo[0].innerHTML 2.document.getElementsByName() 方法 可返回带有制定名称的集合
  2. 元素的父集 parentElement 子集 children nextElementSibling previousElementSibling
  3. 创建节点 document.createElement() appendChild()

##DOM 小练习1. 鼠标按下移动与松开触发 事件## 生活场景:按下鼠标后再移动会带动被选中的div移动,松开停止。

思路如下: a. 先画个定位的DIV
b.监听Mousedown mouseup mousemove
c.定义一个变量来标记是否按下
d.在Move中判断如果按下,则将鼠标位置赋值给div
e. 按下时记录鼠标与div的相对位置,移动时减去这段距离
f.在move时阻止默认行为,防止拖动文字有Bug
g.监听blur事件,防止窗口失去焦点导致bug

<!DOCTYPE html><html lang="en">
<head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Document</title>  
 <style>      
   #demo {  
             width: 300px; 
             height: 300px;            
             background: #ccc;            
             /* user-select: none; */            
             position: absolute;        
             }   
  </style>
 </head>
<body>    
<input type="text">    
<div id="demo">asdfasf</div>    
<script>        
let demo = document.querySelector('#demo')       
 // demo.onmouseover = function () { 
 //     this.style.background = '#f00'       
// }        
 // demo.onmouseout = function () {        
//     this.style.background = '#ccc'        
// }        
let canMove = false        
let x = 0, y = 0       
 demo.onmousedown = function (e) {   
  x = e.pageX - demo.offsetLeft            
  y = e.pageY - demo.offsetTop            
  canMove = true        
  }
  demo.oncontextmenu = function (e) {            
  e.preventDefault()            
  console.log('右键了');        }
   setTimeout(() => {  
   // alert(1)        }, 2000);
   window.onmouseup = function () {     
          canMove = false       
     }
    window.onblur = function () { 
    canMove = false       
     }
   window.onmousemove = function (e) {            
   e.preventDefault(); //阻止默认行为            
   if (canMove) {
   let left = e.pageX - x   let top = e.pageY - y
   if (left < 0) left = 0   if (top < 0) top = 0                
   let maxLeft = window.innerWidth - demo.offsetWidth  
   let maxTop = window.innerHeight - demo.offsetHeight                
   if (left > maxLeft) left = maxLeft  
   if (top > maxTop) top = maxTop
   demo.style.left = left + "px"                
   demo.style.top = top + 'px'           
    }     
  }
        
    </script></body>
</html>