我有以下代码,当你运行代码时,框/块自动从它的位置移动,并在完成一个正方形循环后最终到达起点(Left ->正确的→底→离开→上)。我希望盒子只有在悬停的时候才会移动。原代码为:
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background-color: red;
position: relative;
animation-name: example;
animation-duration: 4s;
}
@keyframes example {
0% {background-color:red; left:0px; top:0px;}
25% {background-color:yellow; left:200px; top:0px;}
50% {background-color:blue; left:200px; top:200px;}
75% {background-color:green; left:0px; top:200px;}
100% {background-color:red; left:0px; top:0px;}
}
</style>
</head>
<body>
<div></div>
</body>
</html>
我试图插入"hover"属性,但它不起作用(代码被完全忽略)。如何修改代码,使块仅在悬停时从其位置移动,而当光标从其上移除时,它会返回到其原始位置?
你需要一个容器来做这件事,试试这个:
<html>
<head>
<style>
.block {
width: 100px;
height: 100px;
background-color: red;
position: relative;
}
.container:hover .block {animation-name: example; animation-duration: 4s;}
@keyframes example {
0% {background-color:red; left:0px; top:0px;}
25% {background-color:yellow; left:200px; top:0px;}
50% {background-color:blue; left:200px; top:200px;}
75% {background-color:green; left:0px; top:200px;}
100% {background-color:red; left:0px; top:0px;}
}
</style>
</head>
<body>
<div class='container'>
<div class='block'></div>
</div>
</body>
</html>
或者,你也可以试试这个。但是要确保你的鼠标一直悬停在块上。
<html>
<head>
<style>
.block {
width: 100px;
height: 100px;
background-color: red;
position: relative;
}
.block:hover {animation-name: example; animation-duration: 4s;}
@keyframes example {
0% {background-color:red; left:0px; top:0px;}
25% {background-color:yellow; left:200px; top:0px;}
50% {background-color:blue; left:200px; top:200px;}
75% {background-color:green; left:0px; top:200px;}
100% {background-color:red; left:0px; top:0px;}
}
</style>
</head>
<body>
<div class='block'></div>
</body>
</html>