目标元素拖动
<div class="box"><div class="title">拖拽效果</div></div>
* {margin: 0;padding: 0;}.box {width: 350px;height: 300px;border: 1px solid #ccc;position: absolute;left: 50%;top: 50%;transform: translate(-50%, -50%);cursor: move;/* 禁止用戶選中 */user-select: none;}.title {width: 100%;height: 50px;line-height: 50px;font-weight: 700;font-size: 30px;color: #fff;text-align: center;border-bottom: 1px solid #ccc;background-color: orange;}
<script>var box = document.querySelector('.box');box.onmousedown = function(e){//獲取鼠標(biāo)按下時候的位置var mx = e.clientX - this.offsetLeft;var my = e.clientY - this.offsetTop;//獲取鼠標(biāo)移動后的距離document.onmousemove = function(e){var xlength = e.clientX - mx;var ylength = e.clientY - my;box.style.left = xlength + 'px';box.style.top = ylength + 'px';}}//鼠標(biāo)抬起box.onmouseup = function() {//移除事件document.onmousemove = null;}</script>
實現(xiàn)效果:
總結(jié)
- 上一篇: js(Dom+Bom)第七天(2)
- 下一篇: 简单的动画函数封装(2)