兼容mouse事件和touch事件,支持IE9及其以上
效果展示:https://jsfiddle.net/shifeng/7xebf3u0/
// index.html
<!DOCTYPE html>
<html lang="en">
<!-- 防止IE提示“Internet Explorer已限制此網頁運行腳本或ActiveX控件” -->
<!-- saved from url=(0014)about:internet -->
<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>Document</title>
<style>
#ballId {
background: rgb(19, 167, 19);
color: white;
width: 50px;
text-align: center;
height: 50px;
line-height: 50px;
border-radius: 50%;
box-shadow: 5px 5px 40px rgba(0, 0, 0, 0.5);
/* 過渡效果在IE下展示效果不友好 */
transition: all 0.08s;
user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
top: 50%;
left: 50%;
transform: translate3d(-50%, -50%, 0);
}
</style>
</head>
<body>
<div id="ballId">drag</div>
<script src="./suspension-ball.js"></script>
<script>
// 使用說明
// 引入suspension-ball.js,調用suspensionBall()方法,第一個參數傳要拖動元素的id,第二個參數傳點擊后的跳轉鏈接
suspensionBall('ballId', 'https://www.baidu.com')
</script>
</body>
</html>
// suspension-ball.js
function suspensionBall(dragId, dragLink) {
var startEvt, moveEvt, endEvt
// 判斷是否支持觸摸事件
if ('ontouchstart' in window) {
startEvt = 'touchstart'
moveEvt = 'touchmove'
endEvt = 'touchend'
} else {
startEvt = 'mousedown'
moveEvt = 'mousemove'
endEvt = 'mouseup'
}
// 獲取元素
var drag = document.getElementById(dragId)
drag.style.position = 'absolute'
drag.style.cursor = 'move'
// 標記是拖曳還是點擊
var isClick = true
var disX, disY, left, top, starX, starY
drag.addEventListener(startEvt, function (e) {
// 阻止頁面的滾動,縮放
e.preventDefault()
// 兼容IE瀏覽器
var e = e || window.event
isClick = true
// 手指按下時的坐標
starX = e.touches ? e.touches[0].clientX : e.clientX
starY = e.touches ? e.touches[0].clientY : e.clientY
// 手指相對於拖動元素左上角的位置
disX = starX - drag.offsetLeft
disY = starY - drag.offsetTop
// 按下之后才監聽后續事件
document.addEventListener(moveEvt, moveFun)
document.addEventListener(endEvt, endFun)
})
function moveFun(e) {
// 兼容IE瀏覽器
var e = e || window.event
// 防止觸摸不靈敏,拖動距離大於20像素就認為不是點擊,小於20就認為是點擊跳轉
if (
Math.abs(starX - (e.touches ? e.touches[0].clientX : e.clientX)) > 20 ||
Math.abs(starY - (e.touches ? e.touches[0].clientY : e.clientY)) > 20
) {
isClick = false
}
left = (e.touches ? e.touches[0].clientX : e.clientX) - disX
top = (e.touches ? e.touches[0].clientY : e.clientY) - disY
// 限制拖拽的X范圍,不能拖出屏幕
if (left < 0) {
left = 0
} else if (left > document.documentElement.clientWidth - drag.offsetWidth) {
left = document.documentElement.clientWidth - drag.offsetWidth
}
// 限制拖拽的Y范圍,不能拖出屏幕
if (top < 0) {
top = 0
} else if (top > document.documentElement.clientHeight - drag.offsetHeight) {
top = document.documentElement.clientHeight - drag.offsetHeight
}
drag.style.left = left + 'px'
drag.style.top = top + 'px'
}
function endFun(e) {
document.removeEventListener(moveEvt, moveFun)
document.removeEventListener(endEvt, endFun)
if (isClick) { // 點擊
window.location.href = dragLink
}
}
}