Why is the object not moving on clicking the button?

后端 未结 3 1014
我在风中等你
我在风中等你 2021-01-28 17:27

The object is not moving on clicking the button. Why is it so?

<
相关标签:
3条回答
  • 2021-01-28 17:33

    If we assume that your element with the object id is the button, then all you need to do is attach an event listener to it so that the animate function is called when you click it.

    const object = document.getElementById('object');
    object.addEventListener('click', animate, false);
    

    Now we just need to rewrite your animate function so that it moves the element associated with the click.

    function animate() {
      var x = 100;
      this.style.left = x + 'px';
    }
    

    DEMO

    If you don't want your button to be that object, add a button to the HTML:

    <button id="button">Click me</button>
    

    then add the event listener to the button:

    const button = document.getElementById('button');
    button.addEventListener('click', animate, false);
    

    And then revert your animate function back to the way it was. Here I've captured the element only in the object variable, as it makes more sense with the variable name you're using.

    function animate() {
      const object = document.getElementById('object');
      var x = 100;
      object.style.left = x + 'px';
    }
    

    DEMO

    Note: if the browsers with which you're working support template literals the last line of your animate function can be:

    object.style.left = `${x}px`;
    
    0 讨论(0)
  • 2021-01-28 17:36

    You would need to include the styling at the end of the statement

    function animate() {
      var x = 100;
      var object = document.getElementById('object').style.left = x + 'px';
    }
    #object {
      position: absolute;
      top: 50px;
      right: 20px;
      left: 20px;
      height: 40px;
      width: 80px;
      background-color: green;
    }

    0 讨论(0)
  • 2021-01-28 17:52

    You should not detach style object from DOM element. Also the name of your function conflicts with native Element.animate function, name your function diffrently.

    This should work:

    function animateX() {
      var object = document.getElementById('object');
      var x = 100;
      object.style.left = x + 'px';
    }
    #object {
      position: absolute;
      top: 50px;
      right: 20px;
      left: 20px;
      height: 40px;
      width: 80px;
      background-color: green;
    }
    <div id="object" onclick="animateX()"></div>

    0 讨论(0)
提交回复
热议问题