【发布时间】:2017-07-09 19:13:01
【问题描述】:
我一直在尝试通过使用 jQuery 对其进行垂直动画处理来使图像看起来像是浮动的。在做了一些挖掘之后,我遇到了这个线程:Animating a div up and down repeatedly 这正是我需要的。将代码应用到我的网站后,我仍然无法弄清楚为什么图像的行为不像示例here。 这是我到目前为止的代码。
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans" rel="stylesheet">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type ="text/javascript" src="script.js"></script>
<!-- Checking to see if running properly
<script>
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
</script> -->
</head>
<body>
<table id="wrapper">
<tr>
<td><img src="PixelBuddah.png" class="bouncer" alt="PixelBuddah" /></td>
</tr>
</table>
<footer>
<p>...</p>
</footer>
</body>
</html>
CSS
html, body, #wrapper {
height:100%;
width: 100%;
margin: 0;
padding: 0;
border: 0;
}
#wrapper td {
vertical-align: middle;
text-align: center;
}
body {
background-color: #F5E9D3;
}
footer {
display: inline-block;
float: right;
text-align: right;
margin: auto;
margin-right: 1.2em;
font-family: 'Noto Sans', sans-serif;
font-weight: 600;
}
Javascript
function loop() {
$('.bouncer').animate({'top': '500'}, {
duration: 1000,
complete: function() {
$('.bouncer').animate({top: 0}, {
duration: 1000,
complete: loop});
}});
$('<div/>').text('exiting loop').appendTo($('.results'));
}
loop();
我对此仍然很陌生,因此感谢您提供任何帮助!谢谢!
【问题讨论】:
-
您的 CSS 缺少这条重要规则
.bouncer { position: absolute; }(您正在为样式的top属性设置动画,除非该位置不是默认位置,否则该属性将被忽略) -
@ChrisG 我添加了这个 CSS,但它只是使 img 不居中。我仍然无法让它动画化。与其使用表格将其居中,不如使用其他方法使其位于浏览器窗口的中心效果更好?
-
你可以使用 CSS 的 flexbox 规则。但这是一个不同的问题。当我添加规则时,您的代码有效:jsfiddle.net/khrismuc/3fuejfjp(另请注意,您在
<head>中添加了两个版本的 jQuery) -
@ChrisG 我已经清除了我的 中的一个 jquery 链接,并且我已经仔细检查了所有代码。但无论出于何种原因,当我在 chrome 中打开 index.html 文件时,我只是没有得到那个动画。我似乎无法找出阻止它运行的原因。
-
您检查浏览器控制台是否有错误?按 F12
标签: javascript jquery html css jquery-animate