如何将css:active伪类传递给javascript?

时间:2016-10-10 20:31:40

标签: javascript html css

参考:Comments由@AnkithAmtange发布

给出html

<div>Click Away</div>

CSS

div {
  width: 200px;
  height: 200px;
  background: orange;
}
div:active {
  color: white;
  background: rebeccapurple;
}

jsfiddle https://jsfiddle.net/u3uhq9m1/

如何将当前:active伪类DOM元素传递给javascript

第一次尝试。注意,jQuery不是必需的。

$(document).ready(function() {
  var active;
  $("div").click(function() {
    active = $(":active");
    setTimeout(function() {
      console.log("active", active)
    }, 1000)
  }) 
})

https://jsfiddle.net/u3uhq9m1/1/

2 个答案:

答案 0 :(得分:7)

您可以使用RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule .* api-index.php?ip=$0 [PT,L]

&#13;
&#13;
document.activeElement
&#13;
$(function() {
  $(document).on('click', function() {
    console.log(document.activeElement);
  });
});
&#13;
&#13;
&#13;

更新

如果您想传递当前的<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="a">asdf</div> <span>123</span> <select> <option>1</option> </select> <button>123</button> <input />元素,则必须使用:active(而不是mousedown事件),因为click元素不再有效一旦你的鼠标启动了。

由于:active冒泡DOM树,所有父元素也将获得:active伪类(在下面的例子中添加了一个红色边框)所以我只采用了最后一个元素:active选择器。

检查此示例:

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

答案 1 :(得分:3)

您可以使用:active:hover伪类animationduration设置为0s@keyframes设置为css; animationend

javascript活动

&#13;
&#13;
:root {
  --activeprop: 0px;
}
div {
  position: relative;
  left: var(--activeprop);
  width: 200px;
  height: 200px;
  background: orange;
}
div:active:hover {
  color: white;
  background: rebeccapurple;
  animation: active 0s;
  -moz-animation: active 0s;
  -webkit-animation: active 0s;
}

@keyframes active {
  from {
    left:var(--activeprop);
  }
  to {
    left:var(--activeprop);
  }
}

@-moz-keyframes active {
  from {
    left:var(--activeprop);
  }
  to {
    left:var(--activeprop);
  }
}
@-webkit-keyframes active {
  from {
    left:var(--activeprop);
  }
  to {
    left:var(--activeprop);
  }
}
&#13;
<div>Click Away</div>
<script>
for (el of document.querySelectorAll("div")) {
el.addEventListener("animationend", function(event) {
  console.log(`${event.target.nodeName} is :active`)
})
};
</script>
&#13;
&#13;
&#13;