jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。CSS 动画则是通过 CSS3 的 @keyframes
规则来定义元素从一种样式逐渐变化到另一种样式的过程。
jQuery 调用 CSS 动画主要有以下几种方式:
animation
或 transition
属性来实现动画效果。.animate()
方法:jQuery 提供了 .animate()
方法,可以实现对元素属性的动画效果。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS 动画示例</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
animation: move 2s infinite;
}
@keyframes move {
0% { transform: translateX(0); }
50% { transform: translateX(200px); }
100% { transform: translateX(0); }
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
.animate()
方法<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 动画示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.box {
width: 100px;
height: 100px;
background-color: blue;
}
</style>
<script>
$(document).ready(function() {
setInterval(function() {
$('.box').animate({ left: '+=100px' }, 1000).animate({ left: '-=100px' }, 1000);
}, 2000);
});
</script>
</head>
<body>
<div class="box"></div>
</body>
</html>
原因:
解决方法:
$(document).ready()
中,确保 DOM 元素加载完成后再执行动画。$(document).ready(function() {
$('.box').animate({ left: '+=100px' }, 1000);
});
原因:
@keyframes
规则定义错误。解决方法:
@keyframes
规则是否正确。.box {
animation: move 2s infinite;
}
通过以上方法,可以有效解决 jQuery 调用 CSS 动画时遇到的常见问题。
没有搜到相关的文章