简体   繁体   English

背景图像不透明度和:hover

[英]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? 仅当光标在div背景图像的不透明部分上时才可以触发div的鼠标悬停吗? Perhaps via Javascript? 也许通过Javascript?

All I can find with Google are old IE PNG fixes. 我可以在Google上找到的只是旧的IE PNG修复程序。

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: 我想也可以通过使用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 . 这仅适用于现代浏览器,但您应该能够使其与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? 进行了一些调整,但是为什么不将类添加到不透明的div中,并使用JavaScript进行检查呢?

In jQuery: 在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. 您将不得不使用大量的Javascript。

You'd want to attach to your <div> 's onmousemove event, which returns the X,Y coordinates of the cursor. 您需要附加到<div>的onmousemove事件,该事件返回光标的X,Y坐标。 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. 然后,您的事件处理程序函数将进行测试,以查看光标是否位于正确的位置,以触发另一个onmouseover事件。

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: 更困难的方法(和更少的浏览器支持)是将背景图像加载到Canvas对象中,然后获取当前像素值的不透明度值并从那里获取它,如下所示:

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. 另一种选择是创建一个完全透明的div(或其他元素),其位置和大小应使其仅覆盖下面div的不透明部分,然后测试该元素框的mouseover

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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