第一种方式:
使用函数调用方式实现
html部分:
<div class="box1"></div>
<div class="box2"></div>
ji部分:
var box1 = document.querySelector('.box1')
var box2 = document.querySelector('.box2')
box2.onmousedown = function (e) {
e = e || window.event
var x = e.pageX-box2.offsetLeft
var y = e.pageY-box2.offsetTop
document.onmousemove = function (e) {
e = e || window.event
var xx = e.pageX - x-1000
var yy = e.pageY -y
if(xx<0){
xx=0
}
if(yy<0){
yy=0
}
if(xx>box1.offsetWidth-box2.offsetWidth){
xx=box1.offsetWidth-box2.offsetWidth
}
if(yy>box1.offsetHeight-box2.offsetHeight){
yy=box1.offsetHeight-box2.offsetHeight
}
box2.style.top = yy + 'px'
box2.style.left = xx + 'px'
}
}
document.onmouseup = function () {
document.onmousemove = ''
}
第二种方式:
使用面向对象方式实现
html部分
<div class="box">
<p class="box1">这是提示信息</p>
</div>
js部分:
<script>
function gte(){
this.pEle = document.querySelector('.box1')
this.bigBoxEle = document.querySelector('.box')
}
gte.prototype.bigBox=function(){
// 鼠标移入事件
this.bigBoxEle.onmouseover = ()=>{
this.pEle.style.display = 'block'
}
// 鼠标移出事件
this.bigBoxEle.onmouseout = ()=>{
this.pEle.style.display = 'none'
}
}
gte.prototype.bigMou=function(){
// 鼠标移动事件
this.bigBoxEle.onmousemove = (e)=>{
// 获取光标坐标位置
e = e || window.event
// 注: 光标坐标相对于大区块
// 获取提示信息区块宽高
let x = e.offsetX - this.pEle.offsetWidth/2
let y = e.offsetY - this.pEle.offsetHeight/2
//左边界检查
if(x < 0){
x = 0
}
// 右边界检查
// 光标坐标不能大于 大区块宽 - 提示信息区块宽
if(x > this.bigBoxEle.offsetWidth - this.pEle.offsetWidth){
x = this.bigBoxEle.offsetWidth - this.pEle.offsetWidth
}
//上边界检查
if(y < 0){
y = 0
}
if(y > this.bigBoxEle.offsetHeight - this.pEle.offsetHeight){
y = this.bigBoxEle.offsetHeight - this.pEle.offsetHeight
}
// 设置光标坐标给提示信息元素
this.pEle.style.left = x + 'px'
this.pEle.style.top = y + 'px'
}
}
const nun=new gte()
nun.bigBox()
nun.bigMou()