首先準備兩個盒子: 再寫樣式: 最後是js代碼部分: 演示效果:http://localhost:63342/demo/work7.html ...
首先準備兩個盒子:
<div id = "oDiv" style = "top:40px;" class = "box"> <div id = "ldiv" style="height:30px ;background: chartreuse "></div> </div>
再寫樣式:
body{
width: 2000px;
height: 2000px;
}
.box{
width: 150px;
height: 200px;
position: absolute;
right: 20px;
border: 1px solid red;
}
.aff{
transition:all 1s;
}
最後是js代碼部分:
function scrollEvent(obj,xEvent,fun){ if(obj.attachEvent){ obj.attachEvent("on"+xEvent,fn); } if(obj.addEventListener){ obj.addEventListener(xEvent,fn, true);//addEventListener w3c標準。 } } window.onload = function (){ dom.addClass($("oDiv"),"aff"); var top = $("oDiv").style.top; top = parseInt(top); scrollEvent(document,"scroll",function(){ var scrollTop = document.documentElement.scrollTop||window.pageYOffset||document.body.scrollTop; var h = scrollTop+top+"px"; $("oDiv").style.top = h; }); $("lDiv").onmousedown = function(){ dom.removeClass($("oDiv"),"aff"); var ev = window.event||event; var sjw = ev.clienX - $("oDiv").offsetLeft; var sjw = ev.clienY - $("oDiv").offsetTop; document.onmousemove = function(){ ev = window.event||event; var x = ev.clienX; var y = ev.clienY; $("oDiv").style.left = (x-sjw)+"px"; $("oDiv").style.top = (y-sjw)+"px"; } } $("lDiv").onmouseup = function(){ dom.addClass($("oDiv"),"aff"); document.onmousemove = null; } }
演示效果:http://localhost:63342/demo/work7.html