<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div style="width: 100px;height: 100px;background-color: red;border: 1px solid black;position: relative;">
</div>
<script>
var box = document.querySelector('div'),
broswerWidth = document.body.clientWidth,
broswerHeight = document.documentElement.clientHeight;
document.onmousedown = function (e) {
to_left = e.clientX - box.offsetLeft;
to_top = e.clientY - box.offsetTop
key = true;
box.style.cursor = 'move'
document.onmousemove = function (e) {
if (key == false) { return}
nx = e.clientX ;ny = e.clientY
box.style.left = nx - to_left + 'px'
box.style.top = ny - to_top + 'px'
//盒子移动后位置=鼠标位置-鼠标相对于盒子的距离
if (box.offsetLeft < 0) {//if判断必须在box.style.left/top下面
box.style.left = 0}
if (box.offsetTop < 0) {
box.style.top = 0}
if (box.offsetLeft + box.clientWidth > broswerWidth) {
box.style.left = broswerWidth - box.clientWidth + 'px'}
if (box.offsetTop + box.clientHeight > broswerHeight) {
box.style.top = broswerHeight - box.clientHeight + 'px' } }
document.onmouseup = function () { //box也可
key = false;
box.style.cursor = 'defalt' }
}
</script>
</body>
</html>
拖拽效果js
最新推荐文章于 2024-10-02 05:39:15 发布
本文介绍了如何使用JavaScript实现网页元素的拖拽功能,包括设置拖拽起点、监听鼠标移动事件、更新元素位置等关键步骤。通过结合HTML和CSS,你可以创建交互性强的拖放用户体验。
摘要由CSDN通过智能技术生成