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



我正在尝试创建一个jQuery脚本,该脚本根据鼠标移动(从background-position:center开始)将背景位置x px向左或向右更改。

这是我到目前为止所拥有的:http://jsfiddle.net/multiformeingegno/KunZ4/530/

$("#salone").bind('mousemove', function (e) {
    $(this).css({
        backgroundPosition: e.pageX + 'px ' + e.pageY + 'px'
    });
});

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

只需减去您要开始的位置:

 backgroundPosition: (e.pageX-650) + 'px ' + (e.pageY-410) + 'px'

要更改速度,请调整鼠标位置的系数:

 backgroundPosition: (e.pageX*2-650) + 'px ' + (e.pageY*2-410) + 'px'

是双倍快。

http://jsfiddle.net/KunZ4/538/

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

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 将图像居中。

从这里取中心计算:如何在 jQuery 中获取背景图像大小?

最新更新