JavaScript+Css标签元素定位;在left:50%;top:50%;transform:translate(-50%,-50%);居中的情况下,使该元素具有移动功能。

项目遇到的,记录一下。

项目场景:

        1、一个弹窗,默认居中,不能有遮罩层。

        2、这个弹窗大小不固定。

        3、可以拖动,但不能超出。

HTML:

<div class="moveEle"></div>

CSS:

* {
    margin: 0;
    padding: 0;
}

.moveEle {
    width: 600px;
    height: 400px;
    background: black;
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

JS:

// 是否可以移动
let drag = false;
// 初始值
let init = {
    // 鼠标的初始位置
    x: null,
    y: null,
    // 和css中的保持一致
    top: 50,
    left: 50,
};

// 获取标签
const ele = document.querySelector('.moveEle')

// 记录元素最后的位置
function recordLastPos() {
    const ele = document.querySelector('.moveEle')
    init.left = ele.style.left.substring(0, ele.style.left.length - 1) * 1
    init.top = ele.style.top.substring(0, ele.style.top.length - 1) * 1
}

// 鼠标按下
ele.addEventListener("mousedown", e => {
    drag = true
    // 记录下鼠标的初始位置
    init.x = e.clientX
    init.y = e.clientY
})

// 鼠标抬起
ele.addEventListener("mouseup", e => {
    drag = false
    recordLastPos()
})

// 鼠标离开元素
ele.addEventListener("mouseleave", e => {
    drag = false
    recordLastPos()
})

// 鼠标移动
ele.addEventListener("mousemove", e => {
    // 当鼠标按下
    if (drag) {
        // 获取标签
        const moveEle = document.querySelector('.moveEle')
        // 获取当前页面的可视区域宽高
        const windowWidth = window.innerWidth
        const windowHeight = window.innerHeight
        // 鼠标当前移动的位置
        const curX = e.clientX
        const curY = e.clientY
        // 鼠标初始位置
        const initX = init.x
        const initY = init.y
        // 位置初始值(百分比)
        let left = init.left
        let top = init.top
        // 计算移动的百分比
        let leftPer = ((curX - initX) / windowWidth) * 100
        let topPer = ((curY - initY) / windowHeight) * 100
        // 计算差值比例
        let leftDiff = windowWidth / (windowWidth - moveEle.clientWidth)
        let topDiff = windowHeight / (windowHeight - moveEle.clientHeight)
        // 计算最终所在位置的百分比
        let moveLeftPer = left + leftPer * leftDiff
        let moveTopPer = top + topPer * topDiff
        // 设定不超出边界
        if (moveLeftPer >= 100) {
            moveLeftPer = 100
        } else if (moveLeftPer <= 0) {
            moveLeftPer = 0
        }
        if (moveTopPer >= 100) {
            moveTopPer = 100
        } else if (moveTopPer <= 0) {
            moveTopPer = 0
        }
        // 更改位置
        moveEle.style.left = moveLeftPer + '%'
        moveEle.style.top = moveTopPer + '%'
        moveEle.style.transform = `translate(-${moveLeftPer}%, -${moveTopPer}%)`
    }
})

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值