最佳答案
可以使用一小段 JavaScript 实现此效果:
JavaScript
document.addEventListener('mousemove', function (event) {
if (window.event) { // IE fix
event = window.event;
}
// Grab the mouse's X-position.
var mousex = event.clientX;
var header = document.getElementById('header');
header.style.backgroundPosition = mousex/3 + 'px 0';
}, false);
工作原理:
- 它在
document
的mousemove
事件上绑定(bind)了一个函数。 - 它使用
event.clientX
获取当前鼠标位置。 - 它以 1/3 的速度 (
mousex/3
) 改变元素#header
的背景位置。 Reference
关于javascript - 相对于光标的 CSS 背景位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29647194/