赞
踩
- <html lang="zh">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>absolute和relative定位示例</title>
- <script src="jquery-1.8.3.min.js"></script>
- <style type="text/css">
- .divFather{
- left: 200px;
- top: 200px;
- position: absolute;/* 绝对定位 */
- height: 300px;
- width: 300px;
- background: #bfb0b0;
- display: flex;/* 设置为弹性布局 */
- justify-content: space-around;/* 内容左右居中显示 */
- align-items: center; /* 内容上下居中显示 */
- z-index: 1;
- }
- .divSon{
- position: relative;/* 绝对定位 */
- height: 150px;
- width: 150px;
- background: #ca7979;
- display: flex;
- justify-content: space-around;
- align-items: center;
- }
- .divGrandson{
- height: 60px;
- width: 60px;
- position: absolute;/* 绝对定位 */
- background: green;
- }
- .moveDiv{
- position: absolute;
- left: 100px;
- top: 50px;
- width: 150px;
- height: 150px;
- background: #d4bfbf;
- display: flex;
- justify-content: space-around;
- align-items: center;
- border-radius: 100px;
- z-index:2;
- }
- </style>
- </head>
- <body>
- <div class="divFather">
- <div class="divSon">
- <div class="divGrandson">
- </div>
- </div>
- </div>
- <div class="moveDiv">
- 我是鼠标拖动模块
- </div>
- <script type="text/javascript">
- // 获取屏幕的高宽度
- let cw = $(window).width();
- let ch = $(window).height();
- // 鼠标按下时获取鼠标在屏幕的位置
- $(".moveDiv").mousedown(function(e){
- e = e || window.event;
- // 获取鼠标在元素上的位置(鼠标按下时在元素上得位置)
- let X = e.clientX - $(".moveDiv").offset().left;
- let Y = e.clientY - $(".moveDiv").offset().top;
-
- $(".moveDiv").mousemove(function(e){
- console.log(cw ,ch);
- e = e || window.event;
- let x = e.clientX - X;
- let y = e.clientY - Y;
- if(x<0)x=0;
- if(y<0)y=0;
- if(x + $('.moveDiv').width() > cw) x = cw-$('.moveDiv').width();
- if(y +$('.moveDiv').height() > ch) y = ch-$('.moveDiv').height();
- $('.moveDiv').css({
- 'left':x,
- 'top':y
- })
- })
- });
- // 鼠标抬起事件
- $(document).mouseup(function(){
- $(".moveDiv").unbind("mousemove")
- })
- </script>
- </body>
- </html>
实际展示效果图:
html代码可以直接复制出去,创建一个demo.html,然后找到jquery引入即可,访问页面可以展示以上效果。
或者直接在本人百度网盘下载即可
链接: https://pan.baidu.com/s/1c5Uy7VbK1PaLIgW8-RvapA 提取码: 3swy
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。