Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 根据鼠标移动将背景位置x px向左/向右移动(从背景位置开始:中间)_Javascript_Jquery_Mouseevent_Background Image - Fatal编程技术网

Javascript 根据鼠标移动将背景位置x px向左/向右移动(从背景位置开始:中间)

Javascript 根据鼠标移动将背景位置x px向左/向右移动(从背景位置开始:中间),javascript,jquery,mouseevent,background-image,Javascript,Jquery,Mouseevent,Background Image,我试图创建一个jQuery脚本,根据鼠标从背景位置:中心开始的移动,将背景位置x px向左或向右更改 以下是我目前掌握的情况: 问题是它不是从背景位置开始:居中,当我移动鼠标时,背景图像从鼠标位置开始,显示白色背景。 我希望它根据鼠标的移动从中心向左/向右移动。并调整背景位置更改动画的速度?只需减去要从中开始的位置: backgroundPosition: (e.pageX-650) + 'px ' + (e.pageY-410) + 'px' 要更改速度,请调整鼠标位置的系数: back

我试图创建一个jQuery脚本,根据鼠标从背景位置:中心开始的移动,将背景位置x px向左或向右更改

以下是我目前掌握的情况:

问题是它不是从背景位置开始:居中,当我移动鼠标时,背景图像从鼠标位置开始,显示白色背景。
我希望它根据鼠标的移动从中心向左/向右移动。并调整背景位置更改动画的速度?

只需减去要从中开始的位置:

 backgroundPosition: (e.pageX-650) + 'px ' + (e.pageY-410) + 'px'
要更改速度,请调整鼠标位置的系数:

 backgroundPosition: (e.pageX*2-650) + 'px ' + (e.pageY*2-410) + 'px'
速度是原来的两倍

对于背景中心的计算,您只需获取图像路径,将其附加到不可见图像,然后获得宽度和高度

var url = $('#myDiv').css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', '');
var bgImg = $('<img />');
bgImg.hide();
scope = this;
bgImg.bind('load', function()
{
   scope.height = $(this).height();
   scope.width = $(this).width();
});
$('#myDiv').append(bgImg);
bgImg.attr('src', url);

var centerX = scope.width/2;
var centerY = scope.height/2;
不,您可以使用centerX和centerY将图像居中

从这里进行中心计算:

是的,我已经暂时使用了它,但我确信有一种方法可以计算出图像的中心,然后从中加上或减去px。Ok对速度有效!现在用一个函数来计算图像的中心,而不是手动设置起始数字,这将是完美的。与此同时,我也在尝试做同样的事情,我调整了一个函数来获得图像的宽度。结果是:我不知道为什么它不平滑。。对我来说,这似乎并没有抓住中心。这很有效:它是上面解决方案的提琴。还是我误解了你?编辑:刚刚删除了警报。完全不向我移动:P
var url = $('#myDiv').css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', '');
var bgImg = $('<img />');
bgImg.hide();
scope = this;
bgImg.bind('load', function()
{
   scope.height = $(this).height();
   scope.width = $(this).width();
});
$('#myDiv').append(bgImg);
bgImg.attr('src', url);

var centerX = scope.width/2;
var centerY = scope.height/2;