【问题标题】:Mouseover Background Movement鼠标悬停背景移动
【发布时间】:2015-05-09 01:33:56
【问题描述】:

当鼠标悬停在 div 上时,我正在尝试进行细微的移动。

然而,其中微妙的部分并不完全奏效。

只要将鼠标悬停在上面,背景图像就会跳动。

$(document).ready(function() {
    var movementStrength = 50;
    var height = movementStrength / $(window).height();
    var width = movementStrength / $(window).width();
    $("#bg").mousemove(function(e){
              var pageX = e.pageX - ($(window).width() / 2);
              var pageY = e.pageY - ($(window).height() / 2);
              var newvalueX = width * pageX * -1 - 25;
              var newvalueY = height * pageY * -1 - 50;
              $('#bg').css("background-position", newvalueX+"px     "+newvalueY+"px");
    });
});

https://jsfiddle.net/cjnLtcr0/2/

【问题讨论】:

  • 您想要延迟或稍微移动一下?
  • 我正在寻找轻微的移动
  • 你可以试试newvalueX / 5 + "px "+newvalueY / 5 +"px"
  • 我试过了,它有点帮助。我在响应式主题上使用它。因此,当窗口的宽度为 250 像素时它会有所帮助,但在任何其他窗口上都没有。我认为这与拉伸背景图像的比例有关。
  • 如果您希望图像在第一次悬停时缓慢滑动而不是跳跃,这可能会变得复杂。

标签: jquery css mousemove


【解决方案1】:

您可以添加一个带有转换的类,使用超时等待转换结束,然后删除该类:

$(document).ready(function() {
  var movementStrength = 50;
  var height = movementStrength / $(window).height();
  var width = movementStrength / $(window).width();
  $("#bg").on({
    mouseenter: function(e) { // on mouse enter
      var pageX = e.pageX - ($(window).width() / 2);
      var pageY = e.pageY - ($(window).height() / 2);
      var newvalueX = width * pageX * -1 - 25;
      var newvalueY = height * pageY * -1 - 50;

      $('#bg').addClass('transition'); // add a transition

      $('#bg').css({ // move background with transition
        "background-position": newvalueX + "px     " + newvalueY + "px"
      });

      setTimeout(function() { // wait .3s
        $('#bg').removeClass('transition'); // remove the transition
      }, 300);
    },

    mousemove: function(e) { // on mouse move
      var pageX = e.pageX - ($(window).width() / 2);
      var pageY = e.pageY - ($(window).height() / 2);
      var newvalueX = width * pageX * -1 - 25;
      var newvalueY = height * pageY * -1 - 50;

      if ($('#bg').hasClass('transition')) { // if there is a transition
        //wait for above timeout to remove transition
      } else { // else no transition

        $('#bg').css({ // move the background without transition
          "background-position": newvalueX + "px     " + newvalueY + "px"
        });
      }
    }
  });
});
#bg {
  background: url('http://netsketched.com/pandf/img/sun-rise-clouds.jpg');
  background-size: 100% 100%;
  width: 250px;
  padding: 100px;
}
.transition {
  /*class with transition*/
  transition: all .3s
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="bg">
  <h2>Hello, world!</h2>
</div>

Documentation for setTimeout

【讨论】:

  • 美丽。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-09
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-12
  • 2011-05-26
相关资源
最近更新 更多