我有.square元素,当我移动鼠标时,应该用鼠标移动它。当我正常移动鼠标时,几乎所有的东西都是好的,但是当我将鼠标快速地移动到右边和底部时,.square框就会转到下边或右边,并形成滚动条。
如何使我的代码比现在的或更好--如何解决这个问题?
注:转换应该有
let square = document.querySelector(".square");
document.addEventListener("mousemove", function (e) {
if (square !== null) {
let x = e.pageX;
let y = e.pageY;
square.setAttribute("style", `top: ${y}px; left: ${x}px`);
let getBottom = square.getBoundingClientRect().bottom;
let getRight = square.getBoundingClientRect().right;
if (getBottom > window.innerHeight) {
square.setAttribute("style", `bottom: 0; left: ${x}px`);
}
if (getRight > window.innerWidth) {
square.setAttribute("style", `top: ${y}px; right: 0`);
}
if (getRight > window.innerWidth && getBottom > window.innerHeight) {
square.setAttribute("style", `bottom: 0; right: 0`);
}
}
});*,
*::before,
*::after{
box-sizing: border-box;
}
body{
margin: 0;
border: 1px solid blue;
}
.square {
position: absolute;
height: 50px;
width: 50px;
border: 5px solid red;
transition: .01s ease-in-out;
}<div class="square"></div>
发布于 2020-06-20 05:22:05
这个问题是由于在CSS中定义了方形元素的位置的转换,再加上在读取其当前位置之前设置了正方形的位置而引起的:
top: ${y}px; left: ${x}px);
可以将方块移出视口,并在鼠标小于方框边长的情况下,从浏览器窗口的底部或右侧创建滚动条。最简单的解决方案是删除CSS转换--将它保持在0.01秒以内,这比监视更新刷新时间要少,而且并不特别有用。
在更新其位置之前,获取一次正方形的位置是另一种解决方案。
在任何一种情况下,最多一次更新正方形的位置可能会更平滑,并将其转换到哪个位置。
在用于查找答案的代码中,html元素的clientWidth和clientHeight属性是这些属性的特例,反映了不包括滚动条的视图端口的大小。转换时间设置为0.05秒,以避免屏幕刷新产生频闪效果:
let square = document.querySelector(".square");
const HTML = document.firstElementChild;
document.addEventListener("mousemove", function (e) {
if (square !== null) {
let domRect = square.getBoundingClientRect()
let x = e.pageX;
let y = e.pageY;
x = Math.min( HTML.clientWidth - domRect.width, x);
y = Math.min( HTML.clientHeight - domRect.height, y);
square.style.top = `${y}px`;
square.style.left = `${x}px`;
//square.setAttribute("style", `top: ${y}px; left: ${x}px`);
}
});*,
*::before,
*::after{
box-sizing: border-box;
}
body{
margin: 0;
border: 1px solid blue;
}
.square {
position: absolute;
height: 50px;
width: 50px;
border: 5px solid red;
transition: .05s ease-in-out;
}<div class="square"></div>
https://stackoverflow.com/questions/62481460
复制相似问题