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

时间:2011-01-07 21:03:26

标签: jquery css raphael

有没有人对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; }

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

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

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

想法?

谢谢!

3 个答案:

答案 0 :(得分:10)

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

var $jQueryObject = $(raphaelObject.node);

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

$jQueryObject.addClass('highlight');

答案 1 :(得分:5)

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

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

然后你可以使用css

来设置它们的样式
#somediv path { fill: white; }
#somediv:hover path { fill: blue; }

答案 2 :(得分:3)

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

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

这将取代

$jQueryObject.addClass('highlight');