简体   繁体   English

相对于光标的CSS背景位置

[英]CSS background position relative to cursor

I'm wondering how to do an effect like this: http://www.gazprom.com/ 我想知道如何产生这样的效果: http : //www.gazprom.com/

(please note, the moving blue background, in top blue menu), and its relativity to cursor position) (请注意,移动的蓝色背景,在顶部的蓝色菜单中)及其与光标位置的相关性)

Is there any script that follows cursor and changes background position style? 是否有任何跟随光标并更改背景位置样式的脚本?

This effect can be achieved using small piece of JavaScript: 使用一小段JavaScript即可达到此效果:

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);

Working Demo 工作演示

How it works : 这个怎么运作 :

  1. It binds a function on the mousemove event on document . 它在documentmousemove事件上绑定了一个函数。
  2. It grabs the current mouse position using event.clientX . 它使用event.clientX当前鼠标位置。
  3. It changes the background-position of element #header with 1/3rd of the speed ( mousex/3 ). 它以速度的mousex/3mousex/3 )更改元素#header的背景位置。 Reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM