简体   繁体   English

在级别中检查元素视口的可见性

[英]Check element viewport visibility in levels

I need to check if a dom-elment is visible in the viewport in different "visibility levels". 我需要检查在不同“可见性级别”下视口中是否可见dom-elment。 I know how to check if it's visible or not, but this time i need an indicator of how visible the element is. 我知道如何检查它是否可见,但是这次我需要一个指示元素是否可见的指示器。 Think of it as 3 colors: Green, Yellow and Red. 可以将其视为3种颜色:绿色,黄色和红色。 Where green is 100% visible and red is not visible at all. 绿色是100%可见而红色完全不可见的地方。

Does anyone have any ideas on how to write jQuery or Javascript for this? 是否有人对此有任何想法要写jQuery或Javascript?

Edit: 0 to 100 would also be a great indicator. 编辑:0到100也将是一个很好的指标。 0 is 0 % visible and 100 is 100% visible. 0是0%可见,100是100%可见。

Fortunately for you, I had to develop almost what you want. 对您来说幸运的是,我不得不开发几乎您想要的东西。 It's a jQuery extension that tells you how visible an element is relative to the browser window. 这是一个jQuery扩展,它告诉您元素相对于浏览器窗口的可见性。 It returns an object with two properties, horizontal and vertical. 它返回具有两个属性的对象,即水平和垂直。 If vertical value is -1, then the element is invisible and over the viewport. 如果垂直值为-1,则该元素在视口上方不可见。 If it is 0, then it's visible. 如果为0,则可见。 If the result if 1, then invisible but under the viewport. 如果结果为1,则在视口下不可见。 Similarly for horizontal . 水平方向也一样

The difference is that '0' doesn't differentiate between 'completely in the viewport' or partially in the viewport. 区别在于,“ 0”不会区分“完全在视口中”还是部分在视口中。 I needed it to determinate if something was above, in, or below the viewport (and the same for left and right). 我需要它来确定视口是在视口的上方,之中还是下方(左侧和右侧相同)。 However, it's a good point to start and it can easily be changed to what you need. 但是,这是一个很好的起点,可以轻松地将其更改为所需的内容。

    jQuery.fn.viewportPosition = function () {
        var $window = $(window);
        var position = this.offset();
        var viewport = { bottom: $window.height(), right: $window.width() };
        var rect = { top: position.top, left: position.left, bottom: position.top + this.height(), right: position.left + this.width() };
        return {
            vertical: (rect.bottom < 0) ? -1 : (rect.top > viewport.bottom) ? 1 : 0,
            horizontal: (rect.left < 0) ? -1 : (rect.left > viewport.right) ? 1 : 0
        };
    };

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

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