简体   繁体   中英

Background-image opacity and :hover

Is it possible to only trigger a div's mouseover when the cursor is over an opaque part of the div's background image? Perhaps via Javascript?

All I can find with Google are old IE PNG fixes.

This looks like a similar question to this one: Hit detection on non-transparent pixel

I suppose this could also be done for background image by getting the attribute with jQuery:

$('#myDiv').css('background-image');

I haven't personally done this, but it seems like a viable solution. This will only work for modern browsers, but you should be able to make it back-compatible with excanvas .

It's a bit of tweaking but why don't you add a class to your opaque div, and use JavaScript to check for it?

In jQuery:

$('div').mouseover(function(){
    if ($(this).is('.opaque')) {
        //Some actions
    }
 });

It is possible, just not very easily. You'll have to use a lot of Javascript.

You'd want to attach to your <div> 's onmousemove event, which returns the X,Y coordinates of the cursor. Your event handler function would then test to see if the cursor is in the correct place in order to trigger an alternative onmouseover event.

Implementing the "is the cursor over an opaque pixel or not?" test can be done two ways: the first is to create a simple mathematical expression (say if the opaque parts of the image make neat rectangles, circles or polygons). The more difficult (and less browser-supported) way is to load the background image into a Canvas object and then get the current pixel value's opacity figure and take it from there, like so:

var pixel = canvas.getImageData(x, y, 1, 1).data;
var alpha = pixel[3]; // assuming RGBA
if( alpha > threshold ) onMouseOver(); // raise the event

Another alternative is to create an entirely transparent div (or some other element) positioned and sized so that it only covers the opaque part of the div below, then just test the mouseover of that element's box.

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