是否可以为raphael元素定义自定义属性?
例如
r.circle(25,50,10).attr({fill:'#b71e16', stroke:'#71140f', 'my_custom_attribute':'a value'});
Run Code Online (Sandbox Code Playgroud)
我需要这个的原因是我想在一整套元素上做一些相当复杂的动画,我想在某处存储每个元素的原始y坐标.
use*_*ca8 41
是您想要的自定义属性:
.attr()和.animate())?我99%确定在Raphael中存储任意数据的官方预期方法是使用该.data()功能,例如
var circle = r.circle(25,50,10).attr({fill:'#b71e16', stroke:'#71140f'});
// set it
circle.data('custom-attribute', 'value');
// get it
data = circle.data('custom-attribute');
alert(data);
Run Code Online (Sandbox Code Playgroud)
请注意,从Raphael 2.1开始,这适用于元素,而不是集合.当我需要将数据分配给一个集合时,我倾向于使用for循环设置它并使用它someSet[0].data()- 一点点污点,但它有效.
烦人的有关文档.data并没有说任何关于它是什么(在写作时)......但.data()在jQuery中,data-*在HTML5,等等等等都有这个目的,使用像这样的作品,和别人说话SO关于打算像这样使用它,所以我非常有信心这是将任意数据附加到Raphael对象的预期方法.
attr()或触发的自定义功能animate()如果你需要一个行为类似Raphael属性的自定义属性 - 当使用attr或更改时触发函数或转换animate(有点像Raphael钩子) - 这就是paper.customAttributes的用途.它定义了一个函数,该函数在为该paper对象中的任何元素设置命名的自定义attr时执行.返回对象应用于元素的标准属性.
官方文档对于这个有一些非常有用的例子,这里是一个改编的:
// A custom attribute with multiple parameters:
paper.customAttributes.hsb = function (h, s, b) {
return {fill: "hsb(" + [h, s, b].join(",") + ")"};
};
var c = paper.circle(10, 10, 10);
// If you want to animate a custom attribute, always set it first - null isNaN
c.attr({hsb: "0.5 .8 1"});
c.animate({hsb: [1, 0, 0.5]}, 1e3);
Run Code Online (Sandbox Code Playgroud)
请注意,this在每个customAttribute执行中,是要为其设置attr的Raphael对象.这意味着...
拉斐尔并不真正支持这一点,所以只有你真的真的需要这样做.但是如果你确实需要拉斐尔不支持的标记中的某些东西,你可以创建一个基本的控件来操纵它attr并animate使用paper.customAttributes和element.node(注意文档element.node几乎只是非常无用的" 不要搞乱"用它 " - 你不应该弄乱它的原因是,它直接给你SVG或VML元素,这意味着Raphael不知道你对它做出的任何改变,这可能会使你的Raphael对象脱离与它控制的元素同步,可能会破坏东西.除非你小心,并使用这样的技术......).
这里是一个例子(假设jQuery也在使用,jQuery不是必需的,但更方便)设置SVG属性dy,它允许你控制Raphael文本的行间距(注意 - 在VML/IE中尚未测试的示例代码).如果它在VML模式下不起作用将更新):
paper.customAttributes.lineHeight = function( value ) {
// Sets the SVG dy attribute, which Raphael doesn't control
var selector = Raphael.svg ? 'tspan' : 'v:textpath';
var $node = $(this.node);
var $tspans = $node.find(selector);
$tspans.each(function(){
// use $(this).attr in jquery v1.6+, fails for SVG in <= v1.5
// probably won't work in IE
this.setAttribute('dy', value );
});
// change no default Raphael attributes
return {};
}
// Then to use it...
var text = paper.text(50,50,"This is \n multi-line \n text");
// If you want to animate a custom attribute, always set it first - null isNaN
text.attr({lineHeight: 0});
text.animate({lineHeight: 100},500);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16624 次 |
| 最近记录: |