简体   繁体   中英

Unable to set element style top or left during mousemove event

TLDR: Here is a 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. 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.

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.

So in onMouseDown, I'm doing just that:

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 = . 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. 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.

  node.style.left = `${rect.x}px`
  node.style.top  = `4{rect.y}px`

FWIW, I swear I tried this at some point but ¯\_(ツ)_/¯

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM