【问题标题】:Timed event versus mouse event定时事件与鼠标事件
【发布时间】:2012-08-20 22:01:52
【问题描述】:

以下脚本设置为由 jQuery mouseenter 事件触发,但现在需要在初始页面滚动时触发,并且每 10 秒重新运行一次,无需用户进行任何交互。令我沮丧的是,我无法使用这些规范创建工作版本。

我怀疑我需要使用 javascript 间隔,但我做的不对。

jQuery(document).ready(function($) {
function calcPoint(x1, y1, degrees, dist) {
    var radians = degrees * (Math.PI / 180);
    var x2 = Math.round(x1 + (Math.sin(radians) * dist));
    var y2 = Math.round(y1 + (Math.cos(radians) * dist));
    return [x2, y2];
}

var $cont  = $('#bubbles');
var $items = $cont.find('li');
var distance = 500; // distance for the items to travel
var duration = 750; // milliseconds
var delay    = 10000; // milliseconds

var explode = function() {
    $items.each(function(i) {
        var $item = $(this);

        // store the original position
        var pos = $item.position();
        if ($item.data('starting') == undefined) {
            $item.data('starting', pos);
        }
        //

        var angle = Math.floor(Math.random()*(360 + 1));
        var dest = calcPoint(pos.left, pos.top, angle, distance);
        $item.animate({
            left: dest[0],
            top:  dest[1],
            opacity: 0,
        }, duration);
    });
};

$cont.one('mouseenter', explode);

$cont.mouseleave(function() {
    $items.each(function() {
        var $item = $(this);
        var dest = $item.data('starting');
        $item.animate({
            left: dest.left,
            top: dest.top,
            opacity: 1
        }, duration);
    });

    setTimeout(function() {
        $cont.one('mouseenter', explode);
    }, delay);
});

【问题讨论】:

标签: jquery scroll jquery-animate setinterval


【解决方案1】:
setInterval(function(){
    $cont.trigger('mouseenter');    
}, 10000);

您可以简单地每 10 秒触发一次mouseenter 事件...

http://api.jquery.com/trigger

【讨论】:

  • 这有点hacky,但它可以让你免于摆弄你的原始代码......
【解决方案2】:

如果您希望它更短 - 插件“jquery-timing”允许以下语法:

$cont.repeat(10000).trigger('mouseenter');

【讨论】:

  • jQuery-timing 看起来不错。感谢您的提示。
猜你喜欢
  • 2020-05-10
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多