Js+css 实现鼠标竖屏拖动功能

<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
body{position:relative;}
*{padding:0;margin:0;}
.dialog{width:400px;height:400px;border:1px solid #ddd;position:fixed;top:100px;left:200px;}
.dialog h2{height:40px;background:purple;cursor:move;}
.mask{position:fixed;width:0;height:0;left:0;top:0;display:none;border: 3px solid #3F51B5;box-shadow: 0px 0px 10px 5px rgba(0, 0, 0, 0.07);cursor:move;}
</style>
</head>
<body>
<div class="dialog" id="box">
<h2 id='digTit'></h2>
</div>
<div class="mask"></div>
<script type="text/javascript">
var dragEle = document.getElementById('digTit');
var box = document.getElementById('box');
var moveBox = document.querySelector('.mask');
var oldX = (document.documentElement.clientWidth-box.offsetWidth)/2;
var oldY = (document.documentElement.clientHeight-box.offsetHeight)/2;
box.style.left = oldX + 'px';
box.style.top = oldY + 'px';
moveBox.style.left = oldX + 'px';
moveBox.style.top = oldY + 'px';
moveBox.style.width = box.offsetWidth + 'px';
moveBox.style.height = box.offsetHeight + 'px';

function startHandler(e) {
moveBox.style.display = 'block';
var beginX = e.touches && e.touches.length > 0 ? e.touches[0].clientX : e.clientX;
var beginY = e.touches && e.touches.length > 0 ? e.touches[0].clientY : e.clientY;
var x, y;

function moveHandler(e) {
if(e.touches && e.touches.length > 0) {
x = oldX + e.touches[0].clientX - beginX;
y = oldY + e.touches[0].clientY - beginY;
} else {
x = oldX + e.clientX - beginX;
y = oldY + e.clientY - beginY;
}
moveBox.style.left = x + 'px';
moveBox.style.top = y + 'px';
}

function endHandler(e) {
box.style.left = x + 'px';
box.style.top = y + 'px';
oldX = x;
oldY = y;
moveBox.style.display = 'none';
document.removeEventListener('mousemove', moveHandler);
document.removeEventListener('mouseup', endHandler);
document.removeEventListener('touchmove', moveHandler);
document.removeEventListener('touchend', endHandler);
}

document.addEventListener('mousemove', moveHandler);
document.addEventListener('mouseup', endHandler);
document.addEventListener('touchmove', moveHandler);
document.addEventListener('touchend', endHandler);
}

box.addEventListener('touchstart', startHandler);
box.addEventListener('mousedown', startHandler);
</script>
</body>
</html> 

posted @   小小菜鸟04  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示