问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 60px;
height: 40px;
background-color: skyblue;
font-size: 20px;
text-align: center;
line-height: 40px;
border-radius: 10px;
margin: 100px auto;
cursor: pointer;
}
.model-box{
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: gray;
opacity: 0.6;
box-sizing: border-box;
}
.model-box .content-box{
position: fixed;
width: 500px;
height: 300px;
box-sizing: border-box;
background-color: white;
box-shadow: 10px 10px 10px black;
border-radius: 10px;
}
.content-box form{
display: flex;
flex-direction: column;
justify-content: center;
margin: 50px 70px;
box-sizing: border-box;
}
.content-box form label {
font-weight: bold;
margin: 10px 0px 10px 0px;
}
.content-box form input{
outline: none;
width: 300px;
height: 40px;
font-size: 20px;
padding: 0px 10px;
}
.content-box button{
position: absolute;
display: block;
width: 100px;
height: 50px;
border: none;
background-color: skyblue;
border-radius: 10px;
float: right;
top: 80%;
left: 35%;
cursor: pointer;
}
.content-box button:hover{
transition: all .3s;
background-color: blue;
color: white;
}
.content-box .close{
float: right;
width: 40px;
height: 40px;
border-radius: 50%;
background-color: white;
box-shadow: 0px 0px 10px gray;
text-align: center;
line-height: 40px;
margin: 10px 20px;
cursor: pointer;
}
.content-box .close:hover{
transition: all .3s;
background-color: blue;
color: white;
}
</style>
<div class="box">登录</div>
<div class="model-box">
<div class="content-box">
<div class="close">X</div>
<form action="">
<label for="">用户名:</label>
<input type="text">
<label for="">密码:</label>
<input type="password">
</form>
<button>登录</button>
</div>
</div>
const box = document.querySelector('.box')
const model = document.querySelector('.model-box')
const closeModel = document.querySelector('.close')
const content = document.querySelector('.content-box')
const title = document.querySelector('.title')
// 注册事件
box.addEventListener('click',()=>{
model.style.display = 'block'
closeModel.addEventListener('click',()=>{
model.style.display = 'none'
})
})
content.addEventListener('mousedown',(e)=>{
const x = e.pageX - content.offsetLeft
const y = e.pageX - content.offsetTop
document.addEventListener('mousemove',move)
function move(e){
const moveX = e.pageX - x
const moveY = e.pageY - y
content.style.left = moveX +'px'
content.style.top = moveY +'px'
}
document.addEventListener('mouseup',function(){
document.removeEventListener('mousemove',move)
})
})
</script>
运行结果及报错内容
在登录页面中点下但不松开,然后页面会跳到鼠标上面去,然后松开,再次在页面中重复此操作,页面离鼠标的位置会越来越远
我的解答思路和尝试过的方法
修改css中的top值,增加title标签进行拖拽操作
我想要达到的结果
页面不会乱跳,鼠标始终在页面中