这是一款jQuery鼠标驱动背景图片动画特效。该特效在鼠标移动悬停到某张缩略图上的时候,全屏背景图片会随之切换为这张缩略图的大图。

使用方法

在页面中引入jquery和style.css。

<link rel="stylesheet" href="css/style.css"/>
<script  src="js/jquery.min.js"></script>        
    
HTML结构

整体布局的HTML结构如下。

<div id="wrap">
  <a href="#" class="hb">
    <div class="c">
      <img src="images/1.jpg" alt=""/>
      <div class="txt">
        <h1>Title here</h1>
        <p>Some longer text here thats wide enough to span on several lines.</p>
      </div>
    </div>
  </a>
  <div class="fullBg">
    <img src="images/1.jpg" alt=""/>
  </div>
  <a href="#" class="hb">
    <div class="c">
      <img src="images/2.jpg" alt=""/>
      <div class="txt">
        <h1>Title here</h1>
        <p>Some longer text here thats wide enough to span on several lines.</p>
      </div>
    </div>
  </a>
  <div class="fullBg">
    <img src="images/2.jpg" alt=""/>
  </div>
  <a href="#" class="hb">
    <div class="c">
      <img src="images/3.jpg" alt=""/>
      <div class="txt">
        <h1>Title here</h1>
        <p>Some longer text here thats wide enough to span on several lines.</p>
      </div>
    </div>
  </a>
  <div class="fullBg">
    <img src="images/3.jpg" alt=""/>
  </div>
  <a href="#" class="hb">
    <div class="c">
      <img src="images/4.jpg" alt=""/>
      <div class="txt">
        <h1>Title here</h1>
        <p>Some longer text here thats wide enough to span on several lines.</p>
      </div>
    </div>
  </a>
  <div class="fullBg">
    <img src="images/4.jpg" alt=""/>
  </div>
</div>
    
初始化插件

在页面DOM元素加载完毕之后,通过下面的方法来初始化该jQuery鼠标驱动背景图片动画特效。

$(document).ready(function(){
  var docWidth = $('body').width(),
      $wrap = $('#wrap'),
      $images = $('#wrap .hb'),
      slidesWidth = $wrap.width();
  
  $(window).on('resize', function(){
    docWidth = $('body').width();
    slidesWidth = $wrap.width();
  })
  
  $(document).mousemove(function(e) {
    var mouseX = e.pageX,
        offset = mouseX / docWidth * slidesWidth - mouseX / 2;
    
    $images.css({
      '-webkit-transform': 'translate3d(' + -offset + 'px,0,0)',
              'transform': 'translate3d(' + -offset + 'px,0,0)'
    });
  });
})
    

该jQuery鼠标驱动背景图片动画特效的codepen网址为:https://codepen.io/web-tiki/pen/oygXeN