元素拖拽的列子,设置拖拽边界值

<!DOCTYPE html>
<html>
<head>
  <style>
    #draggable-element {
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
    }
  </style>
</head>
<body>

<div id="draggable-element"></div>

<script>
var draggableElement = document.getElementById('draggable-element');
var isDragging = false; // 标记是否正在拖动

// 鼠标按下时开始拖动
draggableElement.addEventListener('mousedown', function(event) {
  isDragging = true;

  // 记录当前鼠标位置与元素左上角之间的偏移量
  var offsetX = event.clientX - draggableElement.offsetLeft;
  var offsetY = event.clientY - draggableElement.offsetTop;

   // 在松开鼠标按钮后停止拖动
   document.addEventListener('mouseup', stopDragging);

   function moveElement(event) {
     if (isDragging) {
       var xPosition = event.clientX - offsetX;
       var yPosition = event.clientY - offsetY;

       // 获取屏幕宽度和高度
       var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
       var screenHeight= window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;

        // 检查是否超出屏幕范围,如果是,则限制元素的坐标值在可视区域内
       if (xPosition < 0) {
         xPosition = 0;
       } else if (xPosition + draggableElement.offsetWidth > screenWidth) {
         xPosition = screenWidth - draggableElement.offsetWidth;
       }

       if (yPosition < 0) {
         yPosition = 0;
       } else if (yPosition + draggableElement.offsetHeight > screenHeight) {
         yPosition = screenHeight - draggableElement.offsetHeight;
      }

      // 更新元素的位置
      draggableElement.style.left = xPosition + 'px';
      draggableElement.style.top = yPosition + 'px';
    }
   }

   function stopDragging() {
     isDragging = false;

     // 停止监听移动和松开事件
     document.removeEventListener('mousemove', moveElement);
     document.removeEventListener('mouseup', stopDragging);
   }

   // 随着鼠标移动更新元素位置
   document.addEventListener('mousemove', moveElement);
});
</script>

</body>
</html>

你可能感兴趣的:(html,javascript)