<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body style="height: 5000px" id="wrapper">
<div style=" width: 300px; height: 100px; background:#000;" id="box1"></div>
<div style=" width: 300px; height: 100px; background:red;" id="box2"></div>
<script>
//这里是答题区
</script>
</body>
</html>
题目要求:
当鼠标滚动的时候,box1以鼠标滚动2倍的速度运动,box2以鼠标滚动3倍的速度运动。
自己写的答案:
var box1 = document.getElementById('box1');
var box2 = document.getElementById('box2');
box1.style.position = box2.style.position = 'absolute';
box1.style.marginTop = '0px';
box2.style.marginTop = '100px';
box1.style.transition = 'margin-top 1s';
box1.style.webkitTransition = 'margin-top 1s';
box2.style.transition = 'margin-top 1s';
box2.style.webkitTransition = 'margin-top 1s';
var mouseScroll = function() {
let box1_top = box1.style.marginTop.replace('px', '');
let box2_top = box2.style.marginTop.replace('px', '');
if(arguments[0] < 0) {
box1.style.marginTop = (Number(box1_top) + 2 * 120).toString() + 'px';
box2.style.marginTop = (Number(box2_top) + 3 * 120).toString() + 'px';
} else {
box1.style.marginTop = (Number(box1_top) - 2 * 120).toString() + 'px';
box2.style.marginTop = (Number(box2_top) - 3 * 120).toString() + 'px';
}
}
var scrollFunc = function(e) {
e = e || window.event;
if(e.wheelDelta) { //IE/Opera/Chrome
//自定义事件:编写具体的实现逻辑
mouseScroll(e.wheelDelta);
} else if(e.detail) { //Firefox
//自定义事件:编写具体的实现逻辑
mouseScroll(e.detail);
}
}
if(document.addEventListener) {
document.addEventListener('DOMMouseScroll', scrollFunc, false);
} //W3C
document.onmousewheel = scrollFunc; //IE/Opera/Chrome