【问题标题】:How to animate box border dotted on hover?如何为悬停时点缀的框边框设置动画?
【发布时间】:2019-04-03 11:03:24
【问题描述】:
我需要在悬停时为边框设置动画。
最初盒子的边框会被隐藏,一旦我们将鼠标悬停在盒子上,那个时候点缀的边框就会快速地一个一个动画。
.arrow{
height: 172px;
right: 12px;
width: 140px;
border-right: 2px dotted #2fb89a;
border-bottom: 2px dotted #2fb89a;
top: 5px;
}
<div class="arrow"></div>
【问题讨论】:
-
-
-
-
你真的想用 css 做,还是用 image 可以?或者你可以参考这个答案link
-
标签:
javascript
html
css
transition
【解决方案1】:
尝试使用JS事件mouseover。
创建一个 css 类来执行您想要的操作,然后在该事件中添加/删除该类。
首先,让我们为您的 div 添加一个 id。
那么,事件应该是这样的:
document.getElementById("arrow").addEventListener("mouseover", function(event){
event.target.classList.add("mystyle");
});
现在,您想在“悬停结束”时从 div 中删除该边框,因此我们需要在 mouseleave 事件中删除该类:
document.getElementById("arrow").addEventListener("mouseleave", function(event){
event.target.classList.remove("mystyle");
});
这是代码的快速原始版本。你可以打磨它,让它变得更好。
【解决方案2】:
你可以在 CSS 中只使用伪元素和 :hover:
.arrow{
position:relative;
height: 172px;
right: 12px;
width: 140px;
top: 5px;
}
.arrow::after,
.arrow::before{
position: absolute;
content: '';
display: block;
transition: all 2s;
bottom: 0;
left: 100%;
}
.arrow::after{
border-bottom: 2px dotted #2fb89a;
width: 0;
}
.arrow::before{
border-right: 2px dotted #2fb89a;
height: 0;
top: 100%;
transform: rotateX(180deg);
}
.arrow:hover::after{
width: 100%;
left: 0;
}
.arrow:hover::before{
height: 100%;
top: 0;
}
您可以在此处查看结果。
https://codepen.io/ChemaAlfonso/pen/LvpKMV
希望对你有帮助。