需求1:鼠标移入正方形的时候,蓝色小圆点跟随鼠标滚动(不许蓝色小圆点超出正方形区域),
正方形里实时显示当前鼠标相对于body的坐标。Title (0, 0)
// 当需求为获得的坐标值相对于body时function positionBody(event) { var x, y; var e = event || window.event; x = e.clientX; y = e.clientY; return { x: x, y: y }}function executeMove(event, box, point, dot) { var x = positionBody(event).x; var y = positionBody(event).y; // 获取盒子不计算边框的宽高 var boxWidth = box.clientWidth; var boxHeight = box.clientHeight; var dotWidth = dot.offsetWidth; var dotHeight = dot.offsetHeight; // 边界距离 var borderLeft = boxWidth - dotWidth; var borderTop = boxHeight - dotHeight; if(x >= borderLeft) { dot.style.left = borderLeft + 'px'; } else if (y >= borderTop) { dot.style.top = borderTop + 'px'; } else { dot.style.left = x + 'px'; dot.style.top = y + 'px'; } point.innerHTML = '(' + x + ', ' + y + ')';}window.onload = function () { var box = document.getElementById('box'); var point = document.getElementById('point'); var dot = document.getElementById('dot'); if(box.attachEvent) { box.attachEvent('mousemove', function (event) { executeMove(event, box, point, dot); }); } else { box.addEventListener('mousemove', function (event) { executeMove(event, box, point, dot); }, false); }};
js bin 地址:
需求2:鼠标移入正方形的时候,蓝色小圆点跟随鼠标滚动(不许蓝色小圆点超出正方形区域),
正方形里实时显示当前鼠标相对于正方形的坐标(要求正方形在页面里垂直居中)。元素垂直居中的三种实现方式:
Title (0, 0)
// 当需求为获得的坐标值相对于box时function positionBox(event, box) { var x, y; var e = event || window.event; var boxWidth = box.clientWidth; var boxHeight = box.clientHeight; x = e.clientX - box.offsetLeft; y = e.clientY - (box.offsetTop - box.offsetHeight/2); return { x: x, y: y }}function executeMove(event, box, point, dot) { var x = positionBox(event, box).x; var y = positionBox(event, box).y; // 获取盒子不计算边框的宽高 var boxWidth = box.clientWidth; var boxHeight = box.clientHeight; var dotWidth = dot.offsetWidth; var dotHeight = dot.offsetHeight; // 边界距离 var borderLeft = boxWidth - dotWidth; var borderTop = boxHeight - dotHeight; if(x >= borderLeft) { dot.style.left = borderLeft + 'px'; } else if (y >= borderTop) { dot.style.top = borderTop + 'px'; } else { dot.style.left = x + 'px'; dot.style.top = y + 'px'; } point.innerHTML = '(' + x + ', ' + y + ')';}window.onload = function () { var box = document.getElementById('box'); var point = document.getElementById('point'); var dot = document.getElementById('dot'); if(box.attachEvent) { box.attachEvent('mousemove', function (event) { executeMove(event, box, point, dot); }); } else { box.addEventListener('mousemove', function (event) { executeMove(event, box, point, dot); }, false); }};
js bin: