gpt4 book ai didi

javascript - Box-shadow 响应鼠标位置

转载 作者:行者123 更新时间:2023-12-03 07:05:40 24 4
gpt4 key购买 nike

我正在尝试在网页中创建一个动画,其中元素的框阴影响应鼠标的位置,即(红色 X = 鼠标):
enter image description here
enter image description here
enter image description here
我已经找到了一个跟踪鼠标移动的函数,但我不知道如何将它应用于对象。这是我的代码:

$(document).ready(function() {
function shadowAnimation() {
var objectToAnimate = $("#shadow-test");
document.onmousemove = handleMouseMove;

function handleMouseMove(event) {
var eventDoc, doc, body;

event = event || window.event;

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

console.log(event.pageX + " " + event.pageY);

}
}
});
#shadow-test {
box-shadow: -10px -10px red;
border: 1px solid white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="shadow-test">This is a shadow test</p>

最佳答案

您捕获鼠标位置的逻辑比它需要的要复杂得多。您只需要追踪pageXpageY mousemove 事件。
要移动阴影,您只需计算鼠标到目标元素每个维度的中点的距离。然后,您可以将该距离(受元素的可用高度限制)应用到 box-shadow 的大小。 ,像这样:

jQuery($ => {
let $shadow = $('#shadow-test');
let shadowMax = $shadow.height();
let shadowMin = shadowMax * -1;
let shadowMidPoints = [
$shadow.offset().left + $shadow.width() / 2,
$shadow.offset().top + $shadow.height() / 2
];

$(document).on('mousemove', e => {
let shadowX = Math.min(shadowMax, Math.max(shadowMin, shadowMidPoints[0] - e.pageX));
let shadowY = Math.min(shadowMax, Math.max(shadowMin, shadowMidPoints[1] - e.pageY));
$shadow.css('box-shadow', `${shadowX}px ${shadowY}px red`);
});
});
body {
height: 2000px;
}

#shadow-test {
box-shadow: -10px -10px red;
border: 1px solid white;
margin: 100px;
background-color: #CCC;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p id="shadow-test">This is a shadow test</p>

关于javascript - Box-shadow 响应鼠标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64826383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com