如何使用jQuery将CSS样式应用于Raphael.js对象?

有没有人对Raphael.js SVG库有任何经验?

我正在使用Raphael.js创建一个SVG地图(用于智能手机),但我无法打开Raphael通过jQuery创建外部交互和css样式的地图对象。

var R = Array(); R[1] = new Raphael("level1", 408, 286); R[2] = new Raphael("level2", 408, 286); R[3] = new Raphael("level3", 408, 286); R[4] = new Raphael("level4", 408, 286); R[5] = new Raphael("level5", 408, 286); var attr = { fill: "#ccc", stroke: "#000", "stroke-width": 0.5, "stroke-linecap": "square", "stroke-linejoin": "miter" }; // loop through a bunch of objects (not shown for brevity) // in the end, I end up with a couple hundred objects drawn by Raphael var o = R[fID].path(coordstring).attr(attr); // creates an #o[ID] id value that jQuery can target o.node.id = "o"+$(this).attr('id'); // id value comes from data source o.click(function(){ highlightMapObject(this.node.id.substr(1)); ); // end loop // accessed from the o.click and from outside in jQuery function highlightMapObject(oid){ var $target = $("#o"+oid); $target.addClass('highlight'); } 

我似乎遇到的问题是,尝试向Raphael对象添加一个类不起作用,或者如果它正在工作,那个类的CSS属性(如更改的背景颜色等)没有被应用。

所以如果我的.highlight类是:

 .highlight { background-color: #f00; } 

这要么没有被应用,要么没有覆盖fill:"ccc"来自原始Raphael attrs的fill:"ccc" 。 我的猜测是因为jQuery的目标ID是Raphael对象NODE而不是对象本身,这可能是问题的一部分。

在与Raphael打交道时,我已经看到很多建议完全避免节点,但它似乎是我发现打开Raphael对象直到外部目标(在这种情况下通过jQuery)的唯一方法。

我不必使用CSS来实现这些对象的样式更改,但我必须能够在外部实现更改(通过jQuery – 响应外部突出显示请求等)而不是全部内部(通过Raphael和仅响应对象点击)

想法?

谢谢!

我不确定你的代码是做什么的,但如果你想从Raphael对象中获取一个jQuery对象,那么这样做:

 var $jQueryObject = $(raphaelObject.node); 

从那里你可以使用jQuery来添加一个类:

 $jQueryObject.addClass('highlight'); 

我还发现,如果在使用raphael渲染路径后删除内联样式。

 $('#somediv path').removeAttr('fill').removeAttr('stroke'); 

那么你可以使用css为他们设置你想要的样式

 #somediv path { fill: white; } #somediv:hover path { fill: blue; } 

或者您添加一个类作为属性

 $jQueryObject.attr('class', 'highlight'); 

这将起作用而不是

 $jQueryObject.addClass('highlight');