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

后端 未结 4 1349
旧时难觅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:43

    box.style.left is a string. And in JavaScript if you do string + int the int will be type casted to a string and you get string + string. For instance, if box.style.left is 10px you get:

    '10px' + 1 + 'px'
      int typecasted to string
    '10px' + '1' + 'px'
      create one string
    '10px1px'
    

    And that will be the value of box.style.left. That isn't what you want...

    To solve this you can use parseInt(), which parses a string into an int:

    box.style.left = parseInt(box.style.left) + 1 + "px";
    

    And your if is only matching when the X position of the cursor is exactly the same pixel as box.offsetLeft. That's almost impossible, I don't know what you are trying to do with that if?

    At least, box.style.left has no value the first time. You need to set the value at first to 0 and then use the event.

    A working example will be: http://jsfiddle.net/WouterJ/enLwh/ (please note that I have added position: relative; because we can't use the left property on the current position)


    Some more tips, since you are new to JS:

    • If you do something like this:

      X = X + 12;

      You can short that up as:

      X += 12;

提交回复
热议问题