mousemove parallax 仅轻微移动而不是鼠标位置

mousemove parallax only move slightly instead of mouse position

我希望飞机和火箭在鼠标点击英雄面板区域时仅从其原始位置移动约 5%。

当前代码使图像跟随和偏移鼠标位置。

请协助。

$(document).ready(function () {
    $('#hero-panel').mousemove(function (e) {
        parallax(e, document.getElementById('plane'), 1);
        parallax(e, document.getElementById('rocket'), 2);
    });
});

function parallax(e, target, layer) {
    var layer_coeff = 10 / layer;
    var x = ($(window).width() - target.offsetWidth) / 4 - (e.pageX - ($(window).width() / 4)) / layer_coeff;
    var y = ($(window).height() - target.offsetHeight) / 4 - (e.pageY - ($(window).height() / 4)) / layer_coeff;
    $(target).offset({ top: y ,left : x });
};

https://jsfiddle.net/jc0807/c5yke2on/

谢谢

好的,我想我明白你在找什么: fiddle

$(document).ready(function () {
    var plane = document.getElementById('plane');
    var rocket = document.getElementById('rocket');
    plane.homePos = { x: plane.offsetLeft, y: plane.offsetTop };
    rocket.homePos = { x: rocket.offsetLeft, y: rocket.offsetTop };

    $('#hero-panel').mousemove(function (e) {
        parallax(e, document.getElementById('plane'), 10);
        parallax(e, document.getElementById('rocket'), 20);
    });
});

function parallax(e, target, layer) {
    var x = target.homePos.x - (e.pageX - target.homePos.x) / layer;
    var y = target.homePos.y - (e.pageY - target.homePos.y) / layer;
    $(target).offset({ top: y ,left : x });
};

我们在这里做的是将飞机和火箭的起始位置记录为飞机和火箭对象上的新属性 'homePos'。这使得根据鼠标与对象 homePos 的距离,可以轻松地将视差效果应用为与原始位置的 offset。 如果修改传递给视差的层值,移动量将发生变化(我们将鼠标从对象起始位置中间的偏移量除以它,以计算新的对象偏移量)。

我想我的问题与上面的问题有某种关系,我不想重复。

我正在使用下面的代码 "navigate" 到 mousemove 上的图像中。问题是我无法使图像填满所有可视屏幕区域。我在容器中添加了红色背景以表明我的意思。期望的结果是没有可见的红色背景。

HTML

<div class="m-scene" id="main">
  <div class="scene_element">
    <img class="body" src="http://www.planwallpaper.com/static/images/nature-background-images2.jpg" />
  </div>
</div>

JS

$(document).ready(function() {
  $('img.body').mousemove(function(e) {
    parallax(e, this, 1);
  });
});

function parallax(e, target, layer) {
  var layer_coeff = 20 / layer;
  var x = ($(window).width() - target.offsetWidth) / 2 - (e.pageX - ($(window).width() / 2)) / layer_coeff;
  var y = ($(window).height() - target.offsetHeight) / 2 - (e.pageY - ($(window).height() / 2)) / layer_coeff;
  $(target).offset({
    top: y,
    left: x
  });
};

CSS

.m-scene {
  background-color: red;
  overflow: hidden;
  width: 100%;
}

.scene_element {
  margin-left: auto;
  margin-right: auto;
  overflow: hidden;
}

.scene_element img {
   width: 100%;
  height: auto;
  margin-left: auto;
  margin-right: auto;
}

我的 jsFiddle 是:fiddle

谢谢!