2015-02-23 34 views
1

我試圖獲取視口內可見的給定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; 

任何幫助非常感謝!

+0

「我是想這樣的事情,但水平的值永遠是錯的」 - 請定義「錯誤」,應該發生什麼以及實際發生了什麼?你試圖弄清楚發生了什麼問題? – 2015-02-24 08:54:33

+0

@StephanMuller抱歉不清楚的問題。返回的nElemTotalPxInView從來不是視圖中元素像素的正確編號,因爲計算nHpxInView或nVpxInView的數學運算不正確。我從來沒有完全確定爲什麼,但我的朋友發現了一個更簡單的方法,我會在第二天左右發佈。 – tripRev 2015-02-25 01:03:23

回答

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; 
},