RaphaelJS hide shape onmouseout

丶灬走出姿态 提交于 2019-12-10 23:57:38

问题


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 as display: 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!