Why is this not working ? pushing a box using mouse pointer

后端 未结 4 1348
旧时难觅i
旧时难觅i 2021-01-28 16:23

I\'m a beginner in Javascript, and trying to make a simple script that pushes a box using the mouse pointer. But unfortunately it isn\'t working for some reason, i hope you guys

4条回答
  •  情书的邮戳
    2021-01-28 16:56

    A JQuery version but accomplishes the same as you're trying to do

    http://jsfiddle.net/3mxC3/1/

    The main problem I can see with your script is that e.pageX == box.offsetLeft would mean that it's only going to be triggered when the pageX is exactly the offsetLeft.

    The mousemove event won't be firing every pixel so this approach won't work. The easiest way to accomplish it is to set the mousemove onto the actual box instead (so it'll only fire if the user mouse overs the box)

    Secondly, setting the left attribute on the box was doing nothing as the left/right-ness was being set by the margin: auto. Changing this to position: absolute makes it actually pay attention to the left attribute.

提交回复
热议问题