请在这里查看示例 ☞ jsMove示例
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>demo</title>
<style>
*{margin:0;padding:0;}
html,body{width:100%;height:100%;}
body{height:1000px;}
#div1{width:100px;height:100px;background-color:#660099;position:absolute;right:0px;top:0px;}
#div2{width:100px;height:100px;background-color:#66ccff;position:absolute;left:0px;top:0px;}
</style>
</head>
<body>
<p>滚动鼠标滚轮观察效果</p>
<div id="div1">
</div>
<script>
window.onload = function() {
addPic();
}
function addPic() {
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
window.onscroll = function() {
var scrollY = document.body.scrollTop || document.documentElement.scrollTop;
var clientY = document.documentElement.clientHeight;
var distance = Math.round(scrollY + (clientY - div1.offsetHeight) / 2);
console.log(distance);
onMove(div1, "top", distance, 5);
}
}
/
function onMove(obj, attr, iTarget, iSpeed, fn) {
var timer = null;
var num = 0;
var t = 0; //obj实时move位置
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var t = getStyle(obj, attr);
if (t < iTarget) {
num = Math.ceil((iTarget - t) / iSpeed);
} else {
num = Math.floor((iTarget - t) / iSpeed);
}
if (t == iTarget) {
//console.log(t);
clearInterval(obj.timer);
if (fn) {
fn();
}
} else {
obj.style[attr] = t + num + "px";
}
}, 50)
}
function onOpac(obj, attr, iTarget, iSpeed, fn) {
var timer = null;
var t = 0;
var num = 0;
clearInterval(obj.timer);
obj.timer = setInterval(function() {
t = (getStyle(obj, attr)).toFixed(2) * 100; //要加toFixed
if (t < iTarget) {
num = Math.ceil((iTarget - t) / iSpeed);
} else {
num = Math.floor((iTarget - t) / iSpeed);
}
if (t == iTarget) {
clearInterval(obj.timer);
if (fn) {
fn();
}
} else {
obj.style[attr] = (t + num) / 100;
}
}, 50);
}
function getStyle(obj, attr) {
return parseFloat(getComputedStyle(obj, null)[attr]); //要用parseFloat
}
</script>
</body>
</html>