图像跟随鼠标指针并淡出

时间:2015-07-24 01:53:55

标签: javascript jquery mouseevent fade

我正在尝试创建一个跟随光标的图像并“打印”/绘制自身并淡化在x秒后“打印”/绘制的每个单独图像。

到目前为止,我已经设法让图像跟随光标,只是不确定如何创建一个函数或一种方法,使每个单独的图像在一定时间后消失?

我创建了一个JS Fiddle来帮助我解释。

JS

(function() {
"use strict";

document.onmousemove = handleMouseMove;
function handleMouseMove(event) {
  var imgFollow, eventDoc, doc, body, pageX, pageY;

  event = event || window.event; // IE-ism

  // If pageX/Y aren't available and clientX/Y
  // are, calculate pageX/Y - logic taken from jQuery
  // Calculate pageX/Y if missing and clientX/Y available
  if (event.pageX == null && event.clientX != null) {
    eventDoc = (event.target && event.target.ownerDocument) || document;
    doc = eventDoc.documentElement;
    body = eventDoc.body;

    event.pageX = event.clientX +
      (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
      (doc && doc.clientLeft || body && body.clientLeft || 0);
    event.pageY = event.clientY +
      (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
      (doc && doc.clientTop  || body && body.clientTop  || 0 );
  } 

  // Add an image to follow the cursor     
  imgFollow = document.createElement('div');
  imgFollow.className = "imgFollow";
  imgFollow.style.left = event.pageX + "px";
  imgFollow.style.top = event.pageY + "px";
  document.body.appendChild(imgFollow);

  }
})();

CSS

.wrapper {
  height: 100vh;
  width:100%;
  background-color:green;
  overflow:hidden;
  position:relative;
}
.imgFollow {
  width: 32px;
  height: 32px;
  position: absolute;
  opacity:0.3;
  background-repeat:none;
  background-image:url('http://static.wfu.edu/images/icon-help-32x32.png');
  transform: translate(-50%, -50%);
}

2 个答案:

答案 0 :(得分:2)

添加它们。

<强> JS

setTimeout(function () {
    imgFollow.className = "imgFollow fade-out"
},1000);

<强> CSS

.fade-out{
    transition: opacity 1s;
    opacity: 0 !important;
}

答案 1 :(得分:0)

这是一种使用jquery实现所需内容的方法。

 $(document).ready(function() {
        var init = true;
        $(document).on('click', function() {
            $(this)[init?'on':'off']('mousemove', follow);
            init = !init;
        }).trigger('click');

        function follow(e) {
            var xPos = e.pageX;
            var yPos = e.pageY;
           $("#imgFollow").addClass("imgFollow"); //adds the css class to a div with id "imgFollow" 

            $("#imgFollow").offset({
                left: e.pageX,
                top: e.pageY
            });
        }
    });    

因此,在文档中包含jquery librar并添加一个带有命名id的div。

希望这会有所帮助。