*{
margin: 0;
padding: 0;
list-style: none;
}
#modal{
width: 500px;
height: 400px;
background: #fff;
position: absolute;
/* 页面文字不能被选中 */
user-selsct:none;
}
#modal:hover{
box-shadow: 2px 2px 10px #eee;
}
#contextMenu{
position: absolute;
left: -1000px;
top: 0;
padding: 10px 50px;
background: skyblue;
color: #fff;
}
#layer{
width: 100vw;
height: 100vh;
position: fixed;
z-index: 999;
top: 0;
left:0;
background: rgba(0,0,0,0.2);
display: flex;
justify-content: center;
align-items: center;
}
#title{
display: flex;
justify-content: space-between;
padding: 20px;
background: #F5F5F5;
color: gray;
cursor: move;
}
#close{
cursor: default;
}
登录
删除
function $1(str){
console.log(str)
}
function $2(cn){
return document.getElementById(cn)
}
let layer=$2('layer')
let modal=$2('modal')
let contextMenu=$2('contextMenu')
let close=$2('close')
/**
* 通过一个布尔变量来标记当前鼠标是按下还是抬起
* mousedown中,变量为true
* 在move事件中,判断此变量,如果是true则将当前鼠标位置赋值给div
* mouseup时变量为false,则鼠标移动不再生效
*/
let test=$2('test')
test.οnclick=e =>{
// 阻止链接
e.preventDefault()
}
let canMove=false
let offsetX=0,
offsetY=0
// 关闭弹层
close.οnclick=()=>{
layer.remove()
}
// 右击出现删除对话框
modal.οncοntextmenu= e=>{
$1("右键")
contextMenu.style['left']=e.clientX + "px"
contextMenu.style['top']=e.clientY + "px"
// 阻止默认行为,此处阻止右击时弹出原来的对话框
e.preventDefault()
}
// 实现删除功能
contextMenu.οnclick=e =>{
modal.remove()
contextMenu.style['left']="-1000px"
}
// 做鼠标按下,抬起,及移动效果
title.οnmοusedοwn=e =>{
//当鼠标按下时,记住鼠标在DIV中的位置,便于移动时减掉
$1('鼠标按下')
offsetX=e.pageX-modal.offsetLeft
offsetY=e.pageY-modal.offsetTop
canMove=true
}
window.οnmοuseup= e =>{
$1('鼠标抬起')
canMove=false
}
window.οnmοusemοve= e =>{
let x=e.clientX-offsetX
let y=e.clientY-offsetY
let maxLeft=window.innerWidth-modal.offsetWidth
let maxTop=window.innerHeight-modal.offsetHeight
if(x<0) x=0
else if(x>maxLeft) x=maxLeft
if(y<0) y=0
else if(y>maxTop) y=maxTop
// 阻止默认行为,此处阻止字可以被选中拖拽,不点击盒子也能移动的情况发生
e.preventDefault()
if(canMove){
modal.style['left']=x +"px"
modal.style['top']=y +"px"
}
}
一键复制
编辑
Web IDE
原始数据
按行查看
历史