How to pass css :active pseudo class to javascript?

后端 未结 2 1315
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 08:34

Reference: Comments posted by @AnkithAmtange


Given html

Click Away

css

div {
  width:          


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 09:13

    You can use the document.activeElement for that.

    $(function() {
      $(document).on('click', function() {
        console.log(document.activeElement);
      });
    });
    
    
    asdf
    123

    Update

    If you want to pass the current :active element - you must use the mousedown (and not the click event), because the :active element is not active anymore once your mouse is up.

    Since the :active bubbles up the DOM tree, all the parent elements will also get the :active pseudo-class (added a red border in the following example) so I took only the last element in the $(':active') selector.

    Check this example:

    $(document).ready(function() {
      var active;
      $(document).mousedown(function() {
        active = $(":active");
        setTimeout(function() {
          console.log("active", active.last()[0])
        }, 1000)
      })
    })
    div {
      width: 100px;
      height: 100px;
      background: orange
    }
    div:active {
      color: white;
      background: rebeccapurple
    }
    :active {
      border: 1px solid red;
    }
    
    
    Click Away

提交回复
热议问题