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

10

有谁有使用Raphael.js SVG库的经验吗?

我正在使用Raphael.js创建一个SVG地图(用于智能手机),但我无法通过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; }

这个属性要么没有被应用,要么没有覆盖原始的Raphael attrs中的fill:"ccc"。我的猜测是因为jQuery所针对的ID位于Raphael对象NODE上而不是对象本身,这可能是问题的一部分。

我看到很多建议在处理Raphael时避免使用节点,但这似乎是我发现的唯一一种将Raphael对象公开给外部目标(在这种情况下通过jQuery)的方法。

我不必使用CSS来实现这些对象的样式更改,但我必须能够在外部实现这种变化(通过jQuery-响应外部的高亮请求等),而不是全部内部(通过Raphael并仅响应对象点击)

有什么想法吗?

谢谢!


2
我喜欢Raphael库。我特别 impressed 它如何与jQuery集成得很好。 - Marcus Whybrow
3个回答

10

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

var $jQueryObject = $(raphaelObject.node);

你可以使用jQuery添加一个类:

$jQueryObject.addClass('highlight');

谢谢,非常好用(设置CSS,但不添加类)。我很感激你的帮助。 - Will Henderson
是的,我也不太确定我的代码在做什么 :) - Will Henderson
attr 是 Raphael 属性的映射,而不是 CSS 属性,并且必须使用 attr 应用于 Raphael 对象。一旦您拥有了 jQuery 对象,addClass 就一定会起作用。 - Marcus Whybrow
嗯,看起来我没有正确设置jQuery对象,所以我的代码仍然引用o.node.id = "o"+$(this).attr('id');作为我设置的节点ID值,这就是为什么$target.css(attrs);可以工作但$target.addClass('highlight');不能的原因。我会解决它的。谢谢。 - Will Henderson
请问您能否提供一个例子?先谢谢了。 - Adib Aroui

6
我发现,如果你在使用raphael渲染路径后删除内联样式,则可以达到更好的效果。
$('#somediv path').removeAttr('fill').removeAttr('stroke');

然后您可以使用CSS样式对它们进行任何想要的样式设置。
#somediv path { fill: white; }
#somediv:hover path { fill: blue; }

3
您可以将类作为属性添加。
$jQueryObject.attr('class', 'highlight');

这个可以替代原本的操作。
$jQueryObject.addClass('highlight');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接