js hover悬浮框 不超出屏幕 自动定位

//el表示需要悬浮的框
const el = this.$refs.mouseItem
//根据鼠标位置定位悬浮框
document.addEventListener('mousemove', e => {
    el.style.left = e.clientX + 10 + 'px';
    el.style.top = e.clientY + 10 + 'px';
    // 宽度碰撞检测
    let width = el.offsetWidth;
    if (e.clientX + width + 10 > document.documentElement.clientWidth) {
        el.style.left = e.clientX - width - 10 + 'px';
    }
   //高度碰撞检测
    let height = el.offsetHeight;
    if (e.clientY + height + 10 > document.documentElement.clientHeight) {
        el.style.top = e.clientY - height - 10 + 'px';
    }
});

猜你喜欢

转载自blog.csdn.net/Embrace924/article/details/81095443