我可以用以下代码制作一个跟随鼠标的框。
document.addEventListener('mousemove', (e) => {
document.documentElement.style.setProperty('--mouse-x', e.clientX + 'px');
document.documentElement.style.setProperty('--mouse-y', e.clientY + 'px');
});
.box {
width: 50px;
height: 50px;
background-color: blue;
transform: translate(calc(var(--mouse-x) - 50%), calc(var(--mouse-y) - 50%));
}
<div class="box"></div>
但是一旦元素不在左上角,它就会中断。
document.addEventListener('mousemove', (e) => {
document.documentElement.style.setProperty('--mouse-x', e.clientX + 'px');
document.documentElement.style.setProperty('--mouse-y', e.clientY + 'px');
});
.box {
width: 50px;
height: 50px;
margin-left: 150px;
background-color: blue;
transform: translate(calc(var(--mouse-x) - 50%), calc(var(--mouse-y) - 50%));
}
<div class="box"></div>
如何在转换中使用绝对坐标?我不想使用 left/top/position: fixed/absolute 因为我需要保留元素在流中的位置。
我可以使用 JavaScript 获取中心位置,然后使用该信息获取正确的中心。
document.addEventListener('mousemove', (e) => {
document.documentElement.style.setProperty('--mouse-x', e.clientX + 'px');
document.documentElement.style.setProperty('--mouse-y', e.clientY + 'px');
});
window.addEventListener('load', (e) => {
const box = document.querySelector('.box');
const rect = box.getBoundingClientRect();
box.setAttribute('style', `
--center-x: ${rect.left + (rect.width / 2)}px;
--center-y: ${rect.top + (rect.height / 2)}px;
`);
});
.box {
width: 50px;
height: 50px;
margin-left: 150px;
background-color: blue;
transform: translate(calc(var(--mouse-x) - var(--center-x)), calc(var(--mouse-y) - var(--center-y)));
}
<div class="box"></div>
这是可行的,但它并不理想,而且如果页面中的其他任何内容发生变化,它很容易被破坏。它也会因更多元素而变慢,我希望它尽可能快。有更好的方法吗?我可以使用 CSS/Vanilla JS。
最佳答案
你不必使用 translate()
我建议你使用 CSS 中的 left
和 top
属性。它们可以帮助您根据坐标定位元素。
window.addEventListener('load', (e) => {
const box = document.querySelector('.box');
const rect = box.getBoundingClientRect();
document.addEventListener('mousemove', (e) => {
box.style.left = e.pageX + 'px';
box.style.top = e.pageY + 'px';
});
});
.box {
width: 50px;
height: 50px;
position:absolute;
transform:translate(-50%,-50%);
background-color: blue;
}
<div class="box"></div>
transform: translate()
属性与框的大小相关,但 left
和 top
属性则不然。在某些情况下它也可以更快,因为在您的代码中有很多计算正在进行。然而,这很简单。
关于javascript - 将绝对坐标与 transform translate 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69517764/