如何使用鼠标悬停停止旋转图像?

时间:2012-11-05 03:51:01

标签: javascript html

我已经创建了一个旋转图像的功能,现在我想要做的是在使用mouseover命令时阻止图像旋转。这是我要让图像旋转的js编码

var m = {
Z   : 100,
xm  : 0,
xmm : .25,
ymm : 0,
ym  : 0,
mx  : 0,
nx  : 0,
ny  : 0,
nw  : 0,
nh  : 0,
xR  : 0,
nI  : 0,
scr : 0,
img : 0,

run : function () {
    m.xm += (m.xmm - m.xm) * .1;
    if (m.ym < m.nw * .15) m.ym++;
    m.xR += m.xm;
    for (var i = 0; i < m.nI; i++){
        var A = (i * 360 / m.nI) + m.xR;
        var x = Math.cos(A * (Math.PI / 180));
        var y = Math.sin(A * (Math.PI / 180));
        var a = m.img[i];
        a.style.width  = ''.concat(Math.round(Math.abs(y * m.ym) + y * m.Z), 'px');
        a.style.left   = ''.concat(Math.round((m.nw * .5) + x * ((m.nw * .5) - (m.nw * .05)) - ((Math.abs(y * m.ym) + y * m.Z) * .5)), 'px');
        a.style.height = ''.concat(Math.round(m.ym + y * m.Z), 'px');
        a.style.top    = ''.concat(Math.round((m.nh * .5) - (m.ym * .5) - x * (m.Z * .5) - (m.ymm * y)), 'px');
        a.style.zIndex = 600 + Math.round(y);
        m.setOpacity(a, (y * 50) + 100);
    }
    setTimeout(m.run, 30);
},

2 个答案:

答案 0 :(得分:2)

我真的没有详细阅读你的代码,但你可能做的是在函数外部设置一个参数,也许是旋转图像的函数的全局参数,称之为“旋转”并将其设置为TRUE < / p>

然后,在进行实际旋转之前,检查此“rotate”参数是否设置为TRUE,如果是,则旋转。

现在,onmouseover,您所要做的就是将“rotate”参数设置为FALSE,然后当setTimeout触发器到期并且函数再次启动时它为FALSE时,由于测试失败,imagee将不会旋转

另一种方法是将setTimeout设置为仅在不在mousenotover上时触发,因此如果鼠标悬停,请不要设置超时,否则请设置超时。

这只是我脑海里想到的两个想法,我想你可以考虑一下并决定这些是你喜欢的解决方案,如果没有,那么我会有兴趣知道你的决定。

干杯。

答案 1 :(得分:1)

下一个代码只是一个近似值,更像是一个“伪代码”而不是一个生产代码。无论如何都可以随意修改。

var m = {
run: function() {
    this.isRunning = true;
    // when complete the cycle
    this.cycle = true;
},
play: function() {
    this.timeout = setTimeout((function($this){
        if($this.animCheck !== undefined) clearInterval($this.animCheck);
        $this.run();
    })(this), this.frames);
},
pause: function() {
    this.animCheck = setInterval((function($this) {
        // Obviously, you've to pause the animation when the cycle is finished.
        if($this.cycle) clearTimeout($this.timeout);
    })(this), this.frames);
    return !!this.animCheck;
},
init: function() {
    this.frames = 30;
    this.isRunning = true;
    [the element].addEventListener('mouseover', function() {
        if(this.pause()) this.isRunning = false;
    })
    this.play();
}

};

m.init();