我试图打破JavaScript函数

时间:2014-01-21 20:21:22

标签: javascript jquery

我编写了一个小脚本来制作一个小动画,但是当我在div上快速移动光标10次时,div会移动10次。我创建了一个全局var和一个if查询,但它不起作用。

代码:

var working = false;
$(document).ready(function () {
    $("#div1").attr("style", "position:absolute;top:0px;left:0px;");
    $("#div2").attr("style", "position:absolute;top:0px;right:0px;");
    $("#div3").attr("style", "position:absolute;bottom:0px;left:0px;");
    $("#div4").attr("style", "position:absolute;bottom:0px;right:0px;");
});

function animon(id) {
    if (working == true) return false;
    var working = true;
    if (id == "1") $("#div1").animate({
        position: 'absolute',
        top: '0px',
        left: '60px'
    }, "slow");
    if (id == "2") $("#div2").animate({
        position: 'absolute',
        top: '0px',
        right: '60px'
    }, "slow");
    if (id == "3") $("#div3").animate({
        position: 'absolute',
        bottom: '0px',
        left: '60px'
    }, "slow");
    if (id == "4") $("#div4").animate({
        position: 'absolute',
        bottom: '0px',
        right: '60px'
    }, "slow");
}

function animoff(id) {
    if (id == "1") $("#div1").animate({
        position: 'absolute',
        top: '0px',
        left: '0px'
    }, "slow");
    if (id == "2") $("#div2").animate({
        position: 'absolute',
        top: '0px',
        right: '0px'
    }, "slow");
    if (id == "3") $("#div3").animate({
        position: 'absolute',
        bottom: '0px',
        left: '0px'
    }, "slow");
    if (id == "4") $("#div4").animate({
        position: 'absolute',
        bottom: '0px',
        right: '0px'
    }, "slow");
    var working = false;
}

animon()函数在onmouseover事件和animoff()函数中受限于onmouseout事件。工作布尔值会检查是否移动了div容器。

1 个答案:

答案 0 :(得分:2)

您想使用.stop()

$(document).ready(function(){
    $("#div1").attr("style", "position:absolute;top:0px;left:0px;");
    $("#div2").attr("style", "position:absolute;top:0px;right:0px;");
    $("#div3").attr("style", "position:absolute;bottom:0px;left:0px;");
    $("#div4").attr("style", "position:absolute;bottom:0px;right:0px;");
});
function animon(id){
    if(id=="1")
        $("#div1").stop(true).animate({position:'absolute',top:'0px',left:'60px'},"slow");
    if(id=="2")
        $("#div2").stop(true).animate({position:'absolute',top:'0px',right:'60px'},"slow");
    if(id=="3")
        $("#div3").stop(true).animate({position:'absolute',bottom:'0px',left:'60px'},"slow");
    if(id=="4")
        $("#div4").stop(true).animate({position:'absolute',bottom:'0px',right:'60px'},"slow");
}
function animoff(id){
    if(id=="1")
        $("#div1").stop(true).animate({position:'absolute',top:'0px',left:'0px'},"slow");
    if(id=="2")
        $("#div2").stop(true).animate({position:'absolute',top:'0px',right:'0px'},"slow");
    if(id=="3")
        $("#div3").stop(true).animate({position:'absolute',bottom:'0px',left:'0px'},"slow");
    if(id=="4")
        $("#div4").stop(true).animate({position:'absolute',bottom:'0px',right:'0px'},"slow");
}