Activate an element's :active CSS pseudo-class using Javascript?

后端 未结 1 1297
礼貌的吻别
礼貌的吻别 2020-12-11 03:27

Is this possible?

For example, if a user presses the \"return\" key and I trigger the \"mousedown\" event, how do I also render the element with :active styles?

相关标签:
1条回答
  • 2020-12-11 03:38

    According to the CSS 2.1 spec, the :active pseudo-class applies while:

    an element is being activated by the user. For example, between the times the user presses the mouse button and releases it.

    You should be able to dispatch a mousedown event with the subject element as the event target and it should stay active until a matching mouseup event is dispatched. If it works, it likely won't work reliably on enough browsers to make it useful.

    It would be much simpler (and more widely supported) to add/remove a suitable class.

    Edit

    Here is an example of using DOMActivate. You can see that dispatching an activate event on an element fires the associated onactivate listener, but doesn't change the appearance of the element being activated.

    Perhaps you can simulate actiation by listening for the activate event, adding a class to highlight the element, then remove it after a few moments using setTimeout or similar.

    <style type="text/css">
      p:active {
        background-color: red;
      }
      div:active {
        background-color: green;
      }
    </style>
    
    <script type="text/javascript">
      function Init () {
        var p, ps = document.getElementsByTagName('p');
        var d = document.getElementById('div0');
    
        if (ps.length && ps[0].addEventListener) {
    
          for (var i=0, iLen=ps.length; i<iLen; i++) {
            p = ps[i];
            p.addEventListener ("DOMActivate", onActivate, false);
          }
          d.addEventListener("DOMActivate", onActivate, false);
        }
      }
    
      function onActivate () {
        console.log(this.id + ' has been activated');
      }
    
      function simulateActive(id) {
        var evt = document.createEvent("UIEvents");
        evt.initUIEvent("DOMActivate", true, false, window,1);
    
        var el = document.getElementById(id); 
        var cancelled = !el.dispatchEvent(evt);
    
        if(cancelled) {
          console.log("cancelled");
    
        } else {
          console.log("not cancelled");
        }
      }
    </script>
    
     </head>
    
    <body onload="Init ();">
    
      <div id="div0">div
        <p id="para0">para0</p>
        <p id="para1">para1</p>
        <button onclick="
          simulateActive('para0');
        ">Activate para</button>
      </div>
      <button onclick="
        simulateActive('para0');
      ">Activate para</button>
    
    </body>
    
    0 讨论(0)
提交回复
热议问题