Polymer keypress event handler not being called

2019-02-25 11:03发布

Can't figure out why in the following polymer I am unable to get the keypressHandler function to be called. What am I doing wrong? (I tried putting the on-keypress attribute on the span element itself, but still no cigar.) The rest of the functionality works as expected.

<link rel="import" href="../bower_components/polymer/polymer.html">

<polymer-element name="psq-posscell" attributes="isposs nVal"  on-tap="{{toggle}}" on-keypress="{{keypressHandler}}" >
  <template>
    <link rel="stylesheet" href="../bower_components/polymer-flex-layout/polymer-flex-layout.css" />
    <link rel="stylesheet" href="psq.css" />
    <span class="flexbox align-center justify-center toggle" >{{isposs ? nVal : ' '}}</span>
    <style>
        .toggle {
            float:left; 
            border:1px solid white;
            text-align:center;  
            line-height:2;
            background-color:#f2f2f2;      
        }

        .toggle:hover {
            background-color:#0d2f5a;
            color:white; 
          }

    </style>

  </template>
  <script>
    Polymer('psq-posscell', {
      isposs: true,
      toggle: function() {
        this.isposs = !this.isposs;
        console.log("toggle called");
      },
      ispossChanged: function() {
        console.log("ispossChanged called");
      },
      keypressHandler: function(event, detail, sender) { 
        console.log("key pressed");
      },
    });
  </script>
</polymer-element>

1条回答
女痞
2楼-- · 2019-02-25 11:44

When you press a key, the system has to know where to send the event. This is why there is a concept of focus. For your element to receive keys it must be focused.

You can make it focus-able by setting tabIndex, e.g.

ready: function() { this.tabIndex = 0; }

Now you can cause your element to be focused by calling the focus() method on the element (this.focus()), or by tabbing to it or clicking on it.

Once your element is focused, it should receive key presses.

查看更多
登录 后发表回答