简体   繁体   中英

show() doesn't work when element is hidden

In this jsfiddle the objective is to show the rectangle when the mouse hovers over it, else hide it. The problem is that once the rectangle is hidden, it doesn't show up anymore on hover. Any ideas?

This is the code snippet:

 var paper = Raphael("canvas", 200, 200); var r = paper.rect(5,5, 20, 20); r.attr({ "fill" : "red" }); r.hover( function() { this.show(); // mouse hovers in }, function() { this.hide(); // mouse hovers out }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js"></script> <div id="canvas"></div> 

When you hide an element, You're not technically hovered on that element anymore. That's because hide() sets display:none

You could make it transparent instead of hide it by using opacity

http://jsfiddle.net/gnbkqhus/1/

 var paper = Raphael("canvas", 200, 200); var r = paper.rect(5,5, 20, 20); r.attr({ "fill": "red", "opacity" : "0" }); r.hover( function() { r.attr({ "opacity" : "1" }); }, function() { r.attr({ "opacity" : "0" }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js"></script> <div id="canvas"></div> 

You cannot hover over an invisible element or an undisplayed element. You can hover over a visible element and then use that to show a different previously hidden element. Or you can hover over a transparent element and make it opaque. So instead of

r.hover(
    function() {
        this.show();  // mouse hovers in
    },
    function() {
        this.hide(); // mouse hovers out
    }
);

you need to do

r.hover(
    function() {
        r.attr({ "opacity" : "1" });
    },
    function() {
        r.attr({ "opacity" : "0" });
    }
);

One thing to keep in mind, calling hide() sets the "display" value to "none". And "display:none" elements do not occupy any space on the screen. Therefore any mouse action do not work on them because they have zero height and width.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM