Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

JavaScript E.Listener

I am trying to run a function when user clicks on an rectangle by using eventlistener. So far I only managed to run the function by using onkeydown. The eventListener doesnt work for me. The script tag is place in the body.

<script>
  var teleso = document.getElementById("teleso")
  teleso.addEventListener("click", anim);
  // document.onkeydown = anim;
  var telesoVlevo = 0;



  function anim(e) {



    if (e.keyCode == 37) {
      telesoVlevo -= 2;
      teleso.style.left = telesoVlevo + "px";

      if (telesoVlevo <= 0) {
        telesoVlevo += 2;
      }
    }
  }
</script>
question from:https://stackoverflow.com/questions/65918481/javascript-e-listener

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Even though the question isn't very clear, I think the problem is that you are trying to look for a keycode, while if you try and add:

function anim(e) {
      console.log(e.keyCode);
      }

you'll get undefiend, and that's your problem (click event does not return an e.keyCode value)

so you can actually add to the condition:

function anim(e) {



if (e.keyCode == 37 || e.keyCode === 'undefined') {
  telesoVlevo -= 2;
  teleso.style.left = telesoVlevo + "px";

  if (telesoVlevo <= 0) {
    telesoVlevo += 2;
  }
}

}

of course that's assuming the CSS positioning is properly set: a wrapper that is set to position: realative and the element you're trying to animate, with position: absolute.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...