CSS3 Transitions
transitioncancel 事件在 CSS 转换被取消时触发。
当以下情况时,过渡被取消:
- 应用于目标的transition-property属性的值被更改
- display属性被设置为"none"。
- 转换在运行到完成之前就停止了,例如通过将鼠标移出悬浮过渡元素。
语法
在类似 EventTarget.addEventListener 这样的方法中使用事件名称,或设置事件处理器属性。
addEventListener("transitioncancel", (event) => {});
ontransitioncancel = (event) => {};
示例
在本例中,我们使用 transitionrun 和 transitionend 事件来检测转换何时开始和结束,从而导致在转换期间发生文本更新。这也可以用来触发动画或其他效果,以允许连锁反应。
除此之外,我们也使用 click 事件使盒子消失 (display: none;), 显示如何触发 transitioncancel 事件。
HTML
这只是简单地创建了一个div,我们将在下面用 CSS 样式使其成为一个框,调整大小和改变颜色等。
<div class="box"></div>
CSS
下面的 CSS 样式框和应用一个过渡效果,使框的颜色和大小改变,并导致框旋转,而鼠标光标在它上面。
.box {
margin-left: 70px;
margin-top: 30px;
border-style: solid;
border-width: 1px;
display: block;
width: 100px;
height: 100px;
background-color: #0000ff;
color: #ffffff;
padding: 20px;
font:
bold 1.6em "Helvetica",
"Arial",
sans-serif;
-webkit-transition:
width 2s,
height 2s,
background-color 2s,
-webkit-transform 2s,
color 2s;
transition:
width 2s,
height 2s,
background-color 2s,
transform 2s,
color 2s;
}
.box:hover {
background-color: #ffcccc;
color: #000000;
width: 200px;
height: 200px;
-webkit-transform: rotate(180deg);
transform: rotate(180deg);
}
JavaScript
然后,我们需要建立事件处理程序,以便在转换开始和结束时更改框的文本内容。
let box = document.querySelector(".box");
box.ontransitionrun = function (event) {
box.innerHTML = "Zooming...";
};
box.ontransitionend = function (event) {
box.innerHTML = "Done!";
};
box.onclick = function () {
box.style.display = "none";
timeout = window.setTimeout(appear, 2000);
function appear() {
box.style.display = "block";
}
};
box.ontransitioncancel = function (event) {
console.log(
"transitioncancel fired after " + event.elapsedTime + " seconds.",
);
};
结果
The resulting content looks like this:
示例
Notice what happens when you hover your mouse cursor over the box, then move it away.
Also note the log that appears in the JavaScript console when you click the box, or move the cursor away before the transition has run to completion.
规范
浏览器兼容性
参见
- TransitionEvent 接口
- CSS 属性:transition、transition-delay、transition-duration、transition-property、transition-timing-function
- 相关事件:Element/transitionrun_event、Element/transitionstart_event、Element/transitionend_event
- 以 Document 为目标的该事件:Document/transitioncancel_event
- 以 Window 为目标的该事件:Window/transitioncancel_event
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
