JQUERY move background with mouse movement

三世轮回 提交于 2021-02-19 07:41:31

问题


I have a div with class box1 and it has following css properties(I've given a background image of a random pic from the web)

.box1{
  height:600px;
  width:600px;
  position:absolute;
  background-position:center center;
  background-size:150%;
  top:0;
  left:0;
  background-image:url(http://www.slx-photographic.co.uk/wp-content/uploads/2014/03/Photography-Camera-HD-Wallpaper1.jpg);
}

The question is HOW DO I MOVE THE BACKGROUND with movement of mouse using mousemove(); method of jquery? as of now I've come this far with JQUERY and I can't seem to get it to work

$(document).ready(function(){
    $(document).mousemove(function(e){
      var x = e.pageX;
      var y = e.pageY;

        $(".box1").css({
           ' background-position':'  x/2 +"20px" , y/2 + "20px" '
        });
    });
});

I am trying to change the background position related to movement of mouse so it will be helpful if somebody could explain it if this is not how you do it..


回答1:


You are having the quotes in jquery css method incorrectly. It should be like:

$(".box1").css({
  "background-position": x/2 + "20px ," +  y/2 + "20px"
});

Also you'd need to callibrate your x and y to distances from left of box1 and top box1 repectively. You could subract box1's positions. This might be what you want: https://codepen.io/chrisboon27/pen/rEDIC



来源:https://stackoverflow.com/questions/42316398/jquery-move-background-with-mouse-movement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!