RaphaelJS隐藏形状onmouseout [英] RaphaelJS hide shape onmouseout
问题描述
我使用for循环创建了4个rect.如果将鼠标悬停在任何这些rect上,将在旁边显示rect.但是问题在于,新显示的矩形不会在鼠标移开时隐藏.我的代码有什么问题?
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?
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);
}
}
推荐答案
您遇到了javascript范围问题(以及另外两个较小的问题,请参见下文).
You've got javascript scope problems (plus two other smaller problems, see below).
变量showbox
在函数aa
中定义.因此,您的onmouseout函数看不到它.启动Firebug或浏览器的同等功能,您会看到一堆showbox is not defined
错误.
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.
提示:在使用Raphael时,我通常会创建一个对象或数组,其中包含我创建的所有对象,这些对象或数组的键位易于访问,并且作用域超出了我所有与Raphael相关的功能,因此它们都可以访问它(请参见下面的jsfiddle示例).
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).
如何访问Raphael对象是您需要尽早做出决定的一部分应用程序设计,否则,您将需要做很多重构工作,因为这很痛苦. !).
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:
我添加了解释每个更改的注释.
I added comments explaining each change.
它还解决了另外两个问题:
- (在jsfiddle代码中)在Raphael中没有
display: none;
这样的attr
,请尝试.attr({opacity:0})
或.hide()
... - ...但是...不要!您的mouseover事件创建矩形,您的mouseout事件... 隐藏它们...?您将拥有越来越多的不可见矩形堆栈,这些堆栈最终可能会使某人的浏览器崩溃.先显示然后隐藏,或者先创建再删除-不要先创建再隐藏!
- (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!
mouseover/mouseout事件本身实际上还不错! :-)
The mouseover / mouseout events themselves are actually fine! :-)
这篇关于RaphaelJS隐藏形状onmouseout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!