|
|

楼主 |
发表于 2022-5-17 13:20
|
显示全部楼层
这叫有边界拖拽。全部代码:
- <style>
- .stage {
- margin: auto;
- display: flex;
- justify-content: center;
- align-items: center;
- width: 740px;
- height: 560px;
- background: #eee;
- box-shadow: 1px 1px 2px #666;
- position: relative;
- }
- .stage::before {
- position: absolute;
- content: '图片拖拽不出父元素';
- top: 10px;
- left: 10px;
- font: normal 14px sans-serif;
- }
- .movBox {
- position: absolute;
- width: 120px;
- height: 120px;
- background: #ccc url('/data/attachment/forum/202205/17/131141iqoznnyfo4pqgqna.jpg') no-repeat;
- border-radius: 50%;
- cursor: pointer;
- }
- </style>
- <div class="stage">
- <div class="movBox"></div>
- </div>
- <script>
- let canMove = false;
- let m2pgX, m2pgY,m2eX,m2eY;
- let movBox = document.querySelector('.movBox');
- let stage = document.querySelector('.stage');
- movBox.onmousedown = function(e){
- e = e || event;
- canMove = true;
- m2pgX = e.pageX;
- m2pgY = e.pageY;
- m2eX = m2pgX - this.offsetLeft;
- m2eY = m2pgY - this.offsetTop;
- }
- movBox.onmousemove = function(e){
- if(canMove){
- e = e || event;
- m2pgX = e.pageX;
- m2pgY = e.pageY;
- let eLeft = m2pgX - m2eX;
- if(eLeft < 0) eLeft = 0;
- if(eLeft > stage.clientWidth - this.clientWidth) eLeft = stage.clientWidth - this.clientWidth;
- let eTop = m2pgY - m2eY;
- if(eTop < 0) eTop = 0;
- if(eTop > stage.clientHeight - this.clientHeight) eTop = stage.clientHeight - this.clientHeight;
- this.style.left = eLeft+ 'px';
- this.style.top = eTop + 'px';
- }
- }
- movBox.onmouseup = function() { canMove = false; }
- movBox.onmouseleave = function(){ canMove = false; }
- </script>
复制代码
|
|