我想给表单按钮一个小动画。当我点击"命令"按钮我想更改颜色和文本2秒。 2秒后它将返回原始状态。当我在这2秒窗口中再次单击该按钮时,我想重置旋转。当我点击它一次时它工作。但是,当我快速点击2或3次它不起作用。请看下面我到目前为止所得到的内容。我的主要问题是如何更改我的代码,所以即使多次点击也不会破坏它。
一个小问题: 在我的代码中,我从底部滑入文本,是否可以让它从顶部滑入?
var timerId, delay = 2000;
$(".product-form").submit(function(e){
var button = $(this).find('button[type=submit]'),
order = button.find("span:eq(0)"),
added = button.find("span:eq(1)");
clearTimeout(timerId);
added.hide();
order.hide();
button.addClass("green");
added.slideDown("slow");
timerId = setTimeout(function() {
added.hide();
order.show();
button.removeClass("green");
}, delay);
e.preventDefault();
});

.hide {
display: none
}
#button {
width: 200px;
height: 40px;
border: none;
background: orange;
}
.green {
background: green !important;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="product-form" action="#cart" method="post">
<button id="button" type="submit">
<span>Order</span>
<span class="hide">✓ Added</span>
</button>
</form>
<form class="product-form" action="#cart" method="post">
<button id="button" type="submit">
<span>Order</span>
<span class="hide">✓ Added</span>
</button>
</form>
&#13;
答案 0 :(得分:1)
愚蠢的错误,你在回调中创建了 “timerId” 。每次点击都会。它将创建新的var,不清楚时间。请检查逻辑。否则使用匹配css,如果已添加绿色则返回dnt调用settimeout。
https://codepen.io/deepakshrma/pen/QrBVgQ
<h1>hello</h1>
<div class="alert alert-primary" role="alert">
This is a primary alert—check it out!
<button><i class="fa fa-circle-o-notch fa-spin hidden"></i>Submit</button>
</div>
<div class="alert alert-primary" role="alert">
This is a primary alert—check it out!
<button><i class="fa fa-circle-o-notch fa-spin hidden" ></i>Submit</button>
</div>
.alert button > i.hidden {
display: none;
}
.alert button > i.loading {
display: inline-block;
}
let selected = null;
$(".alert button").click(function (event) {
if(selected){
if( selected === $(this)){
return;
}else {
selected.find('i').removeClass('loading')
selected = $(this);
selected.find('i').addClass('loading')
}
}else {
selected = $(this);
selected.find('i').addClass('loading')
}
setTimeout(function(){
selected.find('i').removeClass('loading')
}, 2000)
console.log($(this))
});
答案 1 :(得分:0)
$(".product-form").submit(function(e){
var timerId, delay = 2000;
var button = $(this).find('button[type=submit]'),
order = button.find("span:eq(0)"),
added = button.find("span:eq(1)");
if(button.attr('disable')) {
return false;
}
else {
button.attr({'disable': 'true'});
}
clearTimeout(timerId);
added.hide();
order.hide();
button.addClass("green");
added.slideDown("slow");
timerId = setTimeout(function() {
added.hide();
order.show();
button.removeClass("green");
button.removeAttr('disable'); /// Note : if you are click multiple times
button.attr({'enable': 'true'});/// duplicate data's will be added.
}, delay);
e.preventDefault();
});
试试吧
如果按钮被禁用,我将返回代码。