html及css样式
<div id="box"></div>
*{padding: 0;margin: 0;}
#box{
width: 100px;
height: 100px;
background: #FFC0CB;
position: absolute;
}
js实现拖动效果
box.onclick=function(e){
// console.log(e.target) //事件源
// console.log(e.clientX,e.clientY) //距离当前窗口距离
// console.log(e.offsetX,e.offsetY) //距离当前被点击物的距离
// console.log(e.pageX,e.pageY) //距离当前页面距离
// console.log(this.offsetWidth,this.offsetHeight) //当前被点击物的宽高
// console.log(window.innerWidth,window.innerHeight) //当前窗口的宽高
// console.log(this.offsetLeft,this.offsetTop)//当前被点击物距离窗口的距离
}
function tuodong (id){
var box =document.getElementById(id)
box.onmousedown=function(e){
var w = e.offsetX
var h = e.offsetY
document.onmousemove= function(e1){
var l = e1.clientX-w
var t = e1.clientY-h
var m = window.innerWidth
var n = window.innerHeight
if (e1.clientX-w<=0) {
l= 0
} else if (e1.clientX-w<=m-box.offsetWidth) {
l = e1.clientX-w
} else{
l = m-box.offsetWidth
}
if (e1.clientY-h<=0){
t=0
}else if (e1.clientY-h<=n-box.offsetHeight) {
t = e1.clientY-h
} else{
t = n-box.offsetHeight
}
box.style.left=l+"px"
box.style.top=t+"px"
box.onmouseup=function(){
document.onmousemove=null
}
}
}
}
tuodong('box')
</script>