我在我的网站上使用了一个小脚本,它跟随用户的光标和一个页面元素。动画有点尖锐,我需要做的是对其应用某种过渡/关键帧。
我尝试使用window.setTimeout
设置延迟,但没有用...我想达到像在这个网站上一样的效果。鼠标移动平稳的地方,有没有办法在不构建巨大的 50kB 库的情况下做到这一点?
document.body.addEventListener("mousemove", function(e) {
var curX = e.clientX;
var curY = e.clientY;
document.getElementById('mouse').style.left = curX - 10 + 'px';
document.getElementById('mouse').style.top = curY - 10 + 'px';
});
body {
height: 500px;
width: 500px;
background: orange;
}
#mouse {
position: fixed;
height: 20px;
width: 20px;
background: black;
top: 40px;
left: 40px;
z-index: 100;
}
<body style="height">
<div id="mouse"></div>
</body>
我希望元素在光标之后平滑移动。目前,它立即遵循确切的路径。
添加一个transition
:
document.body.addEventListener("mousemove", function(e) {
var curX = e.clientX;
var curY = e.clientY;
document.getElementById('mouse').style.left = curX - 10 + 'px';
document.getElementById('mouse').style.top = curY - 10 + 'px';
});
body {
height: 500px;
width: 500px;
background: orange;
}
#mouse {
position: fixed;
height: 20px;
width: 20px;
background: black;
top: 40px;
left: 40px;
z-index: 100;
transition: .1s linear
}
<body style="height">
<div id="mouse"></div>
</body>
在 CodePen 上找到了一个代码片段.. 请参阅下面的链接:
https://codepen.io/renatorib/pen/gBLDA
Javascript代码如下:
$(document).ready(function(){
var mousePos = {};
function getRandomInt(min, max) {
return Math.round(Math.random() * (max - min + 1)) + min;
}
$(window).mousemove(function(e) {
mousePos.x = e.pageX;
mousePos.y = e.pageY;
});
$(window).mouseleave(function(e) {
mousePos.x = -1;
mousePos.y = -1;
});
var draw = setInterval(function(){
if(mousePos.x > 0 && mousePos.y > 0){
var range = 15;
var color = "background: rgb("+getRandomInt(0,255)+","+getRandomInt(0,255)+","+getRandomInt(0,255)+");";
var sizeInt = getRandomInt(10, 30);
size = "height: " + sizeInt + "px; width: " + sizeInt + "px;";
var left = "left: " + getRandomInt(mousePos.x-range-sizeInt, mousePos.x+range) + "px;";
var top = "top: " + getRandomInt(mousePos.y-range-sizeInt, mousePos.y+range) + "px;";
var style = left+top+color+size;
$("<div class='ball' style='" + style + "'></div>").appendTo('#wrap').one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend", function(){$(this).remove();});
}
}, 1);
});
也许这会有所帮助。