javaScript中自定义滚动掉一
html:
<body> <div id="parent"> <div id="son"> </div> </div> <div id="demo"></div> </body>
css:
#parent{ height:30px; width:400px; background:#ccc; position:relative; } #son{ height:30px; width:30px; background:red; position:absolute; cursor:pointer; } #demo{ height:0px; width:0px; background:green; }
javaScript
//接下来,我们就来做这个滚动条的效果滴呀; window.onload=function (){ var parent=document.getElementById("parent"); var son=document.getElementById("son"); var demo=document.getElementById("demo"); son.onmousedown=function (ev){ //这里我们只是拖动x上的改变; var e=ev || event; var relativeX=e.clientX-son.offsetLeft; //y轴上的事情都不用考虑了; // var relativeY=e.clientY-son.offsetTop; //获取鼠标和div执行的相对距离(之间的差值) //事件还是添加在我们document上吧 document.onmousemove=function (ev){ var e=ev || event; var x=e.clientX-relativeX; // var y=e.clientY-relativeY; //限制范围了;这里来显示他们的边界滴 呀 if(x<0){ x=0; }else if(x>(parent.offsetWidth-son.offsetWidth)){ x=parent.offsetWidth-son.offsetWidth; } //这样我们还可以得到一个比例值; //这样是减小 //document.title=Math.abs((son.offsetLeft-parent.offsetWidth))/parent.offsetWidth; //这样是增大 // document.title=1-Math.abs((son.offsetLeft-parent.offsetWidth))/parent.offsetWidth; //利用这个比例,我们可以; //改变某个div的大小 //改变某个div的透明度 //可变物体的可视区; son.style.left=x+'px'; var percent=parseFloat(x/(parent.offsetWidth-son.offsetWidth)); demo.style.height=200*percent+'px'; demo.style.width=200*percent+'px'; //当让我们也可以改变它的透明度 //demo.style.opacity=; //demo.style.filter=alpha(opacity:percent*100) //这样也是可以的 } document.onmouseup=function (){ document.onmousemove=null; document.onmouseup=null; if(son.setCaptrue!=undefined){ son.releaseCaptrue(); } } //当然也要考虑到我们避免“选择文字的”bug if(son.setCaptrue!=undefined){ son.setCaptrue(); } return false; } }
效果: