我正在使用 w3schools 编辑器中的代码,它说明了 jQuery animate function 。
不过,我想尝试使此移动可逆,因此我添加了一个 if/else 语句,以允许 div 在已被单击的情况下向后移动。
这是我在脚本标签之间的代码:
var clicked = false;
$(document).ready(function(){
$("button").click(function(){
if (clicked == false){
$("div").animate({
left: amount,
opacity: '0.5',
height: '150px',
width: '150px'
});
clicked = true;
} else {
$("div").animate({
right: amount,
opacity: '0.5',
height: '150px',
width: '150px'
});
clicked = false;
}
});
});
我知道可能有更好的方法来做到这一点,但我对 jQuery 相当陌生。无论如何,由于 jQuery 只是扩展了 JavaScript,这不起作用似乎很奇怪。
--- 更新:更正了未设置的 amount
并包含整页代码 ---
这是我的新代码。再次单击时 div 仍然不会后移。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var clicked = false;
$(document).ready(function(){
$("button").click(function(){
if (clicked == false){
$("div").animate({
left: '250px'
});
clicked = true;
} else {
$("div").animate({
right: '250px'
});
clicked = false;
}
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
</html>
最佳答案
失败是因为您没有设置金额
!
var clicked = false;
var amount = 0;
$(document).ready(function(){
//more code that calls `amount`
})
检查这个 JSFiddle 以查看它的运行情况:http://jsfiddle.net/1xt58q0a/1/
新的 JSFIddle 来匹配更新的问题:http://jsfiddle.net/1xt58q0a/5/
关于javascript - 为什么我使用 jQuery 的 if/else JS 语句不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31615205/