首页 > 解决方案 > CSS 所有样式都在页面加载时应用过渡

问题描述

我有一些代码可以在悬停时为按钮设置动画,但是当我重新加载页面时,css 会应用我在按钮和按钮文本上设置的 1s 过渡。

我将过渡设置为仅对按钮的宽度起作用,这有效,但是如果我想为多个事物设置动画,我必须选择仅对那些进行动画处理,这有点烦人,因为我以前没有遇到过这个问题。

我在 Chromebook 上使用 Chrome 72.0.3626.122

html {
	width: 100%;
	height: 100%;
}

body,
span {
	margin: 0;
	padding: 0;
}

.button {
	width: 120px;
	height: 40px;
	border: none;
	background-color: salmon;
	transition: 1s ease;
}

.button:hover {
	width: 200px;
}

.button-text {
	color: white;
	font-size: 17px;
	transition: 1s ease;
}

.button:hover .button-text {
	color: lightgray;
}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Button hover</title>
	<link rel="stylesheet" href="style.css">
</head>
<body>
	<button class="button">
		<span class="button-text">Hover me</span>
	</button>
</body>
</html>

这会在页面重新加载后 1 秒内应用所有 css,而不是立即加载所有 css 并在悬停时转换

标签: cssanimationcss-transitions

解决方案


这会在页面重新加载后 1 秒内应用所有 css,而不是立即加载所有 css 并在悬停时转换

所以你希望按钮在页面加载后 1 秒自动变宽,文本变暗,对吗?

CSS 动画应该可以帮助您,因为它们是自调用的,而 CSS 过渡需要触发事件。

// Call the keyframes
.button { animation: expand 0.55s linear 2s 1 normal forwards running; }
.button-text { animation: color-shift 0.55s linear 2s 1 normal forwards running; }

// Keyframes
@keyframes expand {
    0% { width: 120px; }
    100% { width: 200px; }
}

@keyframes color-shift {
    0% { color: white; }
    100% { color: lightgray; }
}

我已经使用你的 HTML 和 CSS 来展示这个 CodePen的不同之处,并提供了一些额外的细节。希望有帮助。


推荐阅读