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

时间:2015-11-27 04:06:45

标签: javascript jquery css offset mousemove

我希望当鼠标击中英雄面板区域时,飞机和火箭只能从原来的位置移动约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/

由于

2 个答案:

答案 0 :(得分:1)

好的,我想我明白你在找什么: 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的鼠标距离,可以容易地将视差效果作为偏移从原始位置应用。 如果修改传递给视差的图层值,则移动量将发生变化(我们将鼠标偏移量除以对象起始位置的中间位置,以计算新的对象偏移量)。

答案 1 :(得分:0)

我想我的问题与上面的问题有某种关系,我不想创建副本。

我正在使用下面的代码"导航"在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

谢谢!