javascript - 将动画添加到 RaphaelJS 切换函数

标签 javascript function animation raphael toggle

我遇到了这段代码并将其“用作”开发我自己的特定切换功能的引用。

Raphael.js - if / else statement not toggling on click

http://jsfiddle.net/YLrzk/1/

我想在每次点击时增加笔划宽度时应用动画。我似乎无法弄清楚如何将此动画与切换功能一起添加。

我认为这将应用于变量 StrONStrOFF 所以我尝试了诸如:

 var strOff = function() {
            this.animate({ 'stroke-width': '1' }, 100);

        }; 

    var strOn  = function() {
            this.animate({ 'stroke-width': '5' }, 100);

        }; 

甚至只是:

var strOff = 
        this.animate({ 'stroke-width': '1' }, 100);



var strOn  = 
        this.animate({ 'stroke-width': '5' }, 100);

对于懒惰的语法,如果我错过了我尝试过的两个示例中的任何内容,我深表歉意。感谢您的帮助。

最佳答案

这些都不起作用,因为 strOn 和 strOff 不是正确的数据类型——它们必须是包含给定矩形的选定和取消选定状态的属性的对象。这代表了对 animate 功能的根本误解:它本质上是 attr 的异步版本。

您可以通过简单地将 strOn 和 strOff 恢复到它们的原始状态然后在给定矩形的点击处理程序中调用它来解决您的问题:

box1.animate( strOn, 100 );
box2.animate( strOff, 100 );
box3.animate( strOff, 100 );

这仍然会给您带来复杂性问题。如果您想添加第四个或第五个矩形,您将很快陷入条件逻辑。在我看来,这种状态信息几乎不应该像这样实现。相反,我建议这样做:

使用单个通用点击处理程序。

var genericClickHandler = function()
{
    //  First step: find and deselect the currently "active" rectangle
    paper.forEach( function( el )
        {
            if ( el.data('box-sel' ) == 1 )
            {
                el.animate( strOff, 100 ).data('box-sel', 0 );
                return false; // stops iteration
            }
        } );
    this.animate( strOn, 100 ).data( 'box-sel', 1 );
}

这将遍历论文中的所有元素——如果其中一个元素被标记为“事件”,它将动画回到其非事件状态。

使用数据来跟踪选定的矩形:

paper.rect( x1, y1, w1, h1 ).attr( {} ).data( 'box-sel', 0 ).click( genericClickHandler );    // note that we're setting data to indicate that this rectangle isn't "active"
paper.rect( x2, y2, w2, h2 ).attr( {} ).data( 'box-sel', 0 ).click( genericClickHandler );
// ... as many rectangles as you like
paper.rect( xN, yN, wN, hN ).attr( {} ).data( 'box-sel', 0 ).click( genericClickHandler );

使用这种方法,无需跟踪单个矩形 - 只需跟踪给定的矩形是否被选中。

这是一个 example supporting many rectangles .

关于javascript - 将动画添加到 RaphaelJS 切换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13834186/

相关文章:

javascript - 运行文本 : Pause, 停止

javascript - Android SQLite 日期 ('now' )不准确

javascript - 如何在没有事件的情况下调用 ember 辛烷模板内的函数?

c++ - 方法和自由函数之间有哪些细微的区别?

javascript - 有没有办法让两个 jQuery 动画同时(正确地)运行?

jquery - 如何在具有悬停事件的 jQuery 动画中正确使用 stop() ?

javascript - 无法在图像周围添加按钮

c++ - 为什么在父类中声明虚函数时出现 Unresolved external 错误?

html - 关键帧动画未在 Safari 中启动

javascript - 设置仅值属性而不是键值