如何使背景图像随光标移动?试图实现这个相互依赖

How would I make my background image move with the cursor? Trying to implement this codepen

本文关键字:实现 依赖 背景 何使 图像 移动 光标      更新时间:2023-09-26

所以我试图得到这个确切的效果:http://codepen.io/chrisboon27/pen/rEDIC

我无法让它在我的代码中工作。

这是我的css和我想要这个效果的位:

#header {
margin: -8px 0 0 0;
background-image:url(img/header_bg.jpg);
background-repeat:no-repeat;
background-position:center;
position:relative;
background-size: cover;

}

<div id="header"> </div>

JS:

    $(document).ready(function() {
var movementStrength = 25;
var height = movementStrength / $(window).height();
var width = movementStrength / $(window).width();
$("#header").mousemove(function(e){
          var pageX = e.pageX - ($(window).width() / 2);
          var pageY = e.pageY - ($(window).height() / 2);
          var newvalueX = width * pageX * -1 - 25;
          var newvalueY = height * pageY * -1 - 50;
          $('#header').css("background-position", newvalueX+"px     "+newvalueY+"px");
});
});

我的css是不同的人的相互依赖的css -这可能是为什么它不工作,但当我改变它,它搞砸了背景(它消失了)。任何帮助将非常感激-我不是很了解js。

谢谢!

编辑:没关系:修复它。

添加position:absoluteposition:fixed将使其工作。position:relative不能计算出height

我想这是因为你忘了在CSS中设置图像的宽度和高度:

#header {
    margin: -8px 0 0 0;
    background-image:url(http://www.brandwatch.com/wp-content/uploads/2012/04/570x320xtrolls.jpg.pagespeed.ic.-hEjJryY-x.jpg);
    background-repeat:no-repeat;
    background-position:center;
    position:relative;
    background-size: cover;
    height: 570px;
    width: 320px;
}
这里的

小提琴