获取视口内的元素像素数

时间:2015-02-23 23:38:06

标签: javascript html dom position viewport

我试图获取在视口内可见的给定html元素的像素总数。这个问题和接受的答案Can I detect the user viewable area on the browser?对于确定元素是在视图中/视图外/部分在视图中非常有用,但对于部分视图情况我需要获得总(垂直x水平)数量像素未被视口遮挡的像素。我正在尝试这样的事情,但水平值总是错误的:

var $element            = $(element),
pos                     = $element.offset(),
elemLeft                = pos.left,
elemTop                 = pos.top,
elemHeight              = $element.outerHeight(), 
elemWidth               = $element.outerWidth(),
winLeft                 = $(top).scrollLeft(), 
winTop                  = $(top).scrollTop(),
winHeight               = $(top).height(), 
winWidth                = $(top).width(),
nElemTotalPx            = elemWidth*elemHeight,
nElemTotalPxInView,
nVpxInView              = elemHeight,
nHpxInView              = elemWidth;

//obscured by bottom of window
if(winTop > elemTop){
    nVpxInView = (elemTop+elemHeight)-winTop;
//obscured by top of window
}else if(winHeight-winTop > elemTop){
    nVpxInView = (winTop+winHeight)-elemTop;
};

//obscured by left of window
if(winLeft > elemLeft){
    nHpxInView = (elemLeft+elemWidth)-winLeft;
//obscured by right of window
}else if(winWidth-winLeft < elemLeft+elemWidth){
    nHpxInView = elemWidth-( elemWidth-(winWidth-winLeft) );
};

nElemTotalPxInView = nVpxInView*nHpxInView;
return nElemTotalPxInView;

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我的朋友找到了解决问题的另一种方法。为视口和元素设置6个值意味着我们总是可以使用单个等式计算视图中像素的百分比:

_getPercentInView = function(element){
    $element = $(element);

    var pos                     = $element.offset(),
        theViewport             = {top:null, left:null, bottom:null, right:null, width:null, height:null},
        theElement              = {top:null, left:null, bottom:null, right:null, width:null, height:null},
        elemLeft                = pos.left,
        elemTop                 = pos.top,
        elemHeight              = $element.height(),
        elemWidth               = $element.width();

    theViewport.width       = $(window).width();
    theViewport.height      = $(window).height();
    theViewport.top         = $(window).scrollTop();
    theViewport.left        = $(window).scrollLeft();
    theViewport.bottom      = theViewport.top+theViewport.height;
    theViewport.right       = theViewport.left+theViewport.width;

    theElement.top          = elemTop - theViewport.top;
    theElement.left         = elemLeft - theViewport.left;
    theElement.width        = elemWidth;
    theElement.height       = elemHeight;
    theElement.bottom       = theElement.top+theElement.height;
    theElement.right        = theElement.left+theElement.width;

    var nPercentInView = Math.round(100 * ((theElement.height-(Math.max(0,0-theElement.top) + Math.max(0,theElement.bottom-theViewport.height))) / theElement.height) * ((theElement.width-(Math.max(0,0-theElement.left) + Math.max(0,theElement.right-theViewport.width))) / theElement.width)   );
    return nPercentInView;
},