在我的页面上,我有一个跟随用户光标的元素。
我想要做的是使用 transform
而不是 top
/left
和普通的 javascript。没有任何库或依赖项...
问题是我需要将存储在变量中的值应用到转换属性。我没有找到任何可以帮助我的东西......
这是我的代码:
var cursor = document.getElementById('cursor');
document.body.addEventListener("mousemove", function(e) {
//storing cursor position as variables
var curX = e.clientX;
var curY = e.clientY;
// I need the code below to be replaced with transform-translate instead of top/left
// I can not get this to work with any other method than top/left
cursor.style.left = curX - 7 + 'px';
cursor.style.top = curY - 7 + 'px';
});
body {
background: orange;
height: 500px;
width: 500px;
}
#cursor {
position: fixed;
z-index: 20000;
height: 14px;
width: 14px;
background-color: #222;
border-radius: 50%;
pointer-events: none!important;
}
<body>
<div id="cursor"></div>
</body>
这是一个简单甚至愚蠢的问题,但我在 stackoverflow 或 google 上没有找到类似的东西......
最佳答案
你可以像下面那样做。不要忘记将 top/left
设置为始终具有相同的行为,因为 translate 将从元素的位置应用平移。
var cursor = document.getElementById('cursor');
document.body.addEventListener("mousemove", function(e) {
//storing cursor position as variables
var curX = e.clientX;
var curY = e.clientY;
// I need the code below to be replaced with transform-translate instead of top/left
// I can not get this to work with any other method than top/left
//cursor.style.left = curX - 7 + 'px';
//cursor.style.top = curY - 7 + 'px';
cursor.style.transform = "translate(" + (curX - 7) + "px," + (curY - 7) + "px)";
});
body {
background: orange;
height: 500px;
width: 500px;
}
#cursor {
position: fixed;
top:0;
left:0;
z-index: 20000;
height: 14px;
width: 14px;
background-color: #222;
border-radius: 50%;
pointer-events: none!important;
}
<body>
<div id="cursor"></div>
</body>
如果您希望它是动态的并使用任何宽度/高度,您可以考虑百分比和
calc()
:var cursor = document.getElementById('cursor');
document.body.addEventListener("mousemove", function(e) {
//storing cursor position as variables
var curX = e.clientX;
var curY = e.clientY;
// I need the code below to be replaced with transform-translate instead of top/left
// I can not get this to work with any other method than top/left
//cursor.style.left = curX - 7 + 'px';
//cursor.style.top = curY - 7 + 'px';
cursor.style.transform = "translate(calc(" + curX + "px - 50%),calc(" + curY + "px - 50%))";
});
body {
background: orange;
height: 500px;
width: 500px;
margin: 0;
}
#cursor {
position: fixed;
top: 0;
left: 0;
z-index: 20000;
height: 14px;
width: 14px;
background-color: #222;
border-radius: 50%;
pointer-events: none!important;
}
<body>
<div id="cursor"></div>
</body>
关于javascript - 尝试在 javascript 中应用 CSS 转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54169955/