这可能吗?
例如,如果用户按下“return”键并且我触发了“mousedown”事件,我该如何渲染带有 :active 样式的元素?
我知道可以使用类来做到这一点,但我更愿意使用预先存在的 :active 样式。
最佳答案
根据CSS 2.1 spec , :active 伪类适用于:
an element is being activated by the user. For example, between the times the user presses the mouse button and releases it.
您应该能够以主题元素作为事件目标来调度 mousedown 事件,并且它应该保持事件状态,直到调度匹配的 mouseup 事件。如果它有效,它可能无法在足够多的浏览器上可靠地工作以使其有用。
添加/删除合适的类会简单得多(并且得到更广泛的支持)。
这里是一个使用 DOMActivate 的例子。您可以看到,在元素上调度激活事件会触发关联的 onactivate 监听器,但不会更改被激活元素的外观。
也许您可以通过监听激活事件来模拟 Action ,添加一个类来突出显示该元素,然后在片刻之后使用 setTimeout 或类似方法将其删除。
<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>
关于javascript - 激活元素的 :active CSS pseudo-class using Javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8101854/