[英]Unable to set element style top or left during mousemove event
TLDR: Here is a JS Fiddle https://jsfiddle.net/qn8jhsaf/10/ TLDR:这是一个 JS Fiddle https://jsfiddle.net/qn8jhsaf/10/
I am attempting to create a simple drag and drop UI using mouse events as I didn't like any of the libraries available for the framework I am using.我正在尝试使用鼠标事件创建一个简单的拖放 UI,因为我不喜欢任何可用于我正在使用的框架的库。 While I have all the events wired up and am getting the application side behavior I want, animating the div moving around isn't working how I would expect.虽然我已经连接了所有事件并获得了我想要的应用程序端行为,但动画 div 移动并没有按照我的预期工作。
I am trying to use vanilla JS to insert a cloned div into the dom, absolutlely position it, and then move it around with tranform: translate as the mouse moves around.我正在尝试使用 vanilla JS 将克隆的 div 插入到 dom 中,绝对是 position 它,然后在鼠标移动时使用 tranform: translate 移动它。
So in onMouseDown, I'm doing just that:所以在 onMouseDown 中,我正在这样做:
const onMouseDown = (e) => {
isDragging = true
const rect = element.getBoundingClientRect()
let node = element.cloneNode(true)
node.style.position = 'absolute'
node.style.zIndex = 1000
node.style.left = rect.x
node.style.top = rect.y
console.log(rect.x)
console.log(node.style.left)
draggableNode = node
document.body.append(node)
}
The curious part happens when I call node.style.left =
.奇怪的部分发生在我调用node.style.left =
时。 It does not throw an error or anything but the value remains stubbornly empty ( ""
) and it does not get translated to the style attribute of the cloned div.它不会抛出错误或任何东西,但该值仍然是顽固的空( ""
)并且它不会被转换为克隆 div 的样式属性。 As far as I can tell from documentation this is a supported thing.据我从文档中可以看出,这是受支持的。 I'm not sure what else to try.我不确定还能尝试什么。
The left and top styles need to be strings.左上角 styles 需要是字符串。
node.style.left = `${rect.x}px`
node.style.top = `4{rect.y}px`
FWIW, I swear I tried this at some point but ¯\_(ツ)_/¯
FWIW,我发誓我在某个时候尝试过,但是¯\_(ツ)_/¯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.