1,介绍
图片根据鼠标移动进行浮动,首先根据鼠标移动以屏幕中心点为中心计算鼠标移动的方向(上下左右),根据移动方向设置动画样式。
GIF效果图如下:
3,源码
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <style> html, body { width: 100%; display: flex; text-align: center; align-items: center; justify-content: center; height: 100%; padding: 0; margin: 0; } </style> <body> <img id="shapan" src="images/001.jpeg" /> </body> <script src="js/jquery.js"></script> <script> let w = 1920; let h = 1080; let dirName = new Array('top', 'right', 'bottom', 'left'); window.onmousemove = function(e) { let x = (e.pageX - (w / 2)) * (w > h ? (h / w) : 1); let y = (e.pageY - (h / 2)) * (h > w ? (w / h) : 1); let direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4; let dirText = dirName[direction]; let nx = x / 22; let ny = y / 22; spiritEffect(dirText, Math.abs(nx), Math.abs(ny)); } function spiritEffect(fo, nx, ny) { if (fo == 'top') { $(`#shapan`).css('transform', `translateY(${ny}px)`) } if (fo == "bottom") { $(`#shapan`).css('transform', `translateY(${-ny}px)`) } if (fo == 'left') { $(`#shapan`).css('transform', `translateX(${nx}px)`) } if (fo == "right") { $(`#shapan`).css('transform', `translateX(${-nx}px)`) } $(`#shapan`).css('transition', `0.35s`) } </script> </html>