jquery实现拖拽小方块效果
(编辑:jimmy 日期: 2025/10/24 浏览:3 次 )
今天来讲一个很常用的拖拽功能,主要是利用一点css,js和jquery,很简单但同时也很重要,掌握好才是最关键的!
下面来看下效果图:
这里可以看到,在鼠标hover的时候会有一个透明度的变化和一个盒子阴影!并且在右下角会实时的显示出小方块移动时横纵坐标的变化!
可以看到有一个盒子阴影
在鼠标单击按住的时候会变红,然后可以拖动小块随意移动
我们在看代码之前可以先了解下jquery中的基本知识(选择器,css控制器什么的)和offset()和clientX,clientY。思路很简单,就是分别监听鼠标的 mousedown,mouseup,mousemove这三个事件,通过判断div移动之前的坐标,div移动之后的坐标(offset获得)和鼠标移动前后的坐标(clientX和clientY获得)判断div在body里的具体坐标位置,然后设置div在body里左边和上边的距离(left,top)。代码思路在代码里很详细!希望大家好好理解!
附上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖动图片</title>
<style>
html {
height: 100%;
}
body {
margin: 0px;
padding: 0rem;
border: 0rem;
height: 100%;
width: 100%;
position: relative;
/* 取消默认的输入事件,不然会一直出现‘I'一样的光标 */
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#drag {
height: 200px;
width: 200px;
background: teal;
border: none;
border-radius: 1rem;
/* 一定要是absolute */
position: absolute;
opacity: 0.8;
}
#drag:hover {
box-shadow: 0 8px 12px 0 rgba(16, 49, 231, 0.4);
opacity: 1;
cursor: pointer;
}
input {
width: 12rem;
height: 2rem;
font-size: 1.5rem;
border: 2px solid #aaa;
}
#input1 {
display: block;
position: absolute;
bottom: 1.2rem;
right: 1rem;
}
#input2 {
display: block;
position: absolute;
bottom: 1.2rem;
right: 16rem;
}
</style>
</head>
<body>
<div id="drag">
</div>
<input type="text" id="input1" name="y" placeholder="y轴的坐标为">
<input type="text" id="input2" name="x" placeholder="x轴的坐标为">
<!-- 引入内部jquery,大家使用可以引入CDN -->
<script src="/UploadFiles/2021-04-02/jquery-3.5.1.min.js">
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇:js实现弹幕墙效果


