图像跟随鼠标指针和淡出

Image follow mouse pointer and fades

本文关键字:淡出 鼠标指针 跟随 图像      更新时间:2023-09-26

我正在尝试创建一个图像,跟随光标和'打印'/绘制自己,并褪去已'打印'/x秒后绘制的每个单独的图像。

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

我已经创建了一个JS提琴来帮助我的解释。

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%);
}

添加。

JS

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

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

这是一种使用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库,并添加一个div与您的命名id。

希望这对你有帮助。