js在自己给定的大框里实现拖拽


<!DOCTYPE html>
< html lang= "en">
< 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 lang= "">
* {
margin: 0;
padding: 0;
}
#div1 {
width: 40 px;
height: 40 px;
background: blue;
position: absolute;
left: 450 px;
top: 200 px;
}
#div2 {
width: 600 px;
height: 400 px;
background: #f0f0f0;
position: relative;
margin: 50 px auto 0;
}
</ style>
</ head>
< body>
< div id= "div2">
< div id= "div1"></ div>
</ div>
< script>
var oDiv =document. getElementById( 'div1');
var sh = false
var offsetLeftIn
var offsetTopIn
document. onmousemove = function( ev){
if(sh){
var curLeft
var curTop
curLeft =(ev.clientX -offsetLeftIn) > 0 ?ev.clientX -offsetLeftIn : 0
curLeft =(curLeft) <(oDiv.parentNode.offsetWidth -oDiv.offsetWidth) ?(curLeft) :(oDiv.parentNode.offsetWidth -oDiv.offsetWidth);
// if(curLeft>window.innerWidth-2*oDiv.offsetWidth){
// curLeft=window.innerWidth-oDiv.offsetWidth;
// }
// curLeft=offsetLeftIn;
oDiv.style.left =curLeft + 'px';
// console.log(oDiv.style.left)
curTop =(ev.clientY -offsetTopIn) > 0 ?(ev.clientY -offsetTopIn) : 0
curTop =(curTop) <(oDiv.parentNode.offsetHeight -oDiv.offsetWidth) ?(curTop) :(oDiv.parentNode.offsetHeight -oDiv.offsetWidth)
console. log(curTop)
oDiv.style.top =curTop + 'px';
}
}
oDiv. onmousedown = function( ev){
// console.log(oDiv.offsetLeft)
// console.log(ev.clientX)
offsetLeftIn =ev.clientX -oDiv.offsetLeft //是在小滑块里的偏移量+大框在Body里的偏移量
offsetTopIn =ev.clientY -oDiv.offsetTop
console. log(offsetTopIn)
sh = true
}
document. onmouseup = function( ev){
sh = false
}
</ script>
</ body>
</ html>

首先每次拖拽都是一个按下动作接着很多移动的动作的过程,按下时就确定了光标在滑块里的偏移量。以后怎么移动这个值都不变。但要注意ev.clientX是在body下的偏移量,而oDiv.offsetLeft则是滑块在大框里的偏移量,所以ev.clientX-oDiv.offsetLeft

得到的是在小滑块里的偏移量加大框在body里的偏移量。把这个量记为offsetLeftIn

然后根据这个恒等式:

offsetLeftIn+当前的滑块在外框偏移量=当前光标在body里的偏移量

就可以求出当前的滑块在外框偏移量

然后把oDiv.style.left设置成这个值即可。

这个可以用来做音量调节的那种效果,只需要把外框和滑块的大小调节合适即可。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值