我遇到了这段代码并将其“用作”开发我自己的特定切换功能的引用。
Raphael.js - if / else statement not toggling on click
我想在每次点击时增加笔划宽度时应用动画。我似乎无法弄清楚如何将此动画与切换功能一起添加。
我认为这将应用于变量 StrON
和 StrOFF
所以我尝试了诸如:
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 );
使用这种方法,无需跟踪单个矩形 - 只需跟踪给定的矩形是否被选中。
关于javascript - 将动画添加到 RaphaelJS 切换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13834186/