问题
I've created 4 rects using for loop. If you hover on any of these rects a rect will be displayed alongside. But the problem is that newly displayed rect doesn't hide on mouse out. What is wrong with my code?
JS Fiddle
window.onload = function() {
var paper = Raphael(0, 0, 640, 540);
function aa(h1,h2){
var showbox = paper.rect(h1+300,h2,100,100);
}
function ab(){
showbox.hide();
}
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
(function(i, j) {
var boxes = paper.rect(0 + (j * 100), 0 + (i * 100), 100, 100).attr({
fill: '#303030',
stroke: 'white'
});
boxes.node.onmouseover = function() {
var h1 = boxes.getBBox().x;
var h2 = boxes.getBBox().y;
aa(h1,h2);
};
boxes.node.onmouseout = function() {
ab();
};
})(i, j);
}
}
回答1:
You've got javascript scope problems (plus two other smaller problems, see below).
The variable showbox
is defined within function aa
. So your onmouseout function can't see it. Get Firebug or your browser's equivalent up and you'll see a stack of showbox is not defined
errors.
Tip: When working with Raphael, I usually create an object or array that contains all my created objects, keyed for easy access and scoped above all my Raphael-related functions so all of them can access it (see jsfiddle example below).
How to access your Raphael objects is a piece of application design you need to decide on early on, else you'll need to do lots of refactoring further down the line (been there, it hurts!).
Here's an adapted version of your code that works:
jsfiddle
Edit: I added comments explaining each change.
It also fixes two other problems:
- (In the jsfiddle code) No such
attr
asdisplay: none;
in Raphael, try.attr({opacity:0})
or.hide()
... - ...BUT... don't! Your mouseover event creates rectangles, your mouseout event... hides them...? You're going to have an ever-growing stack of invisible rectangles that could eventually crash someone's browser. Either show, then hide, or create, then remove - don't create then hide!
The mouseover / mouseout events themselves are actually fine! :-)
来源:https://stackoverflow.com/questions/13884682/raphaeljs-hide-shape-onmouseout