# JS

# contenteditable 输入属性

任何属性都可以增加这个,增了之后就可以输入了

<div id="divmove" contenteditable>

</div>

# 可见宽度 & 高度

# offset

offset = width / height / padding / border

  • offsetWidth
  • offsetHeight

client = width / height / padding

  • clientWidth
  • clientHeight

# 边缘距离

HTML元素都拥有 offsetTop,offsetLeft属性,可以返回当前元素距离某个父辈元素左或上边缘的距离,这两个属性是只读属性

如果父辈元素中有定位的元素,那么就返回距离当前元素最近的定位元素的边缘的距离 如果父辈元素中没有定位元素,那么就返回相对于body边缘距离

# 拖拽效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<style>
    * {
        padding: 0;
        margin: 0;
    }

    #divmove {
        width: 100px;
        height: 100px;
        background-color: pink;
        position: absolute;
        left: 0;
    }

</style>
<body>
<div id="divmove">

</div>
</body>

<script>
    let element = document.getElementById("divmove");
    element.onmousedown = function (mouseDownRes) {
        //计算当前鼠标的x和y
        const x = mouseDownRes.clientX - element.offsetLeft;
        const y = mouseDownRes.clientY - element.offsetTop;

        //最大x
        const maxX = innerWidth - element.offsetWidth;
        //最大Y
        const maxY = innerHeight - element.offsetHeight;

        document.onmousemove = function (moveRes) {
            //文档的移动元素 - 鼠标的x和y
            let needX = moveRes.clientX - x;
            let needY = moveRes.clientY - y;

            //不超出边界
            if(needX < 0) needX = 0;
            if(needY < 0) needY = 0;

            if (needX > maxX) needX = maxX;
            if (needY > maxY) needY = maxY;

            element.style.left =`${needX}px`;
            element.style.top = `${needY}px`;
        };
        document.onmouseup = function (res) {
            document.onmousemove = null;
            document.onmouseup = null;
        };
    };

</script>
</html>