2012-08-02 116 views
0

我有这个JS代码在弹出框中显示滚动过去时div的id值。当ID看起来像这样时它工作正常:id =“1”。但我怎么能改变它来检测一个id,如下所示:id =“1:1”或id =“23:4”?两个数字用冒号分隔。在滚动条上显示Div ID

<div id="sayverse"></div> 
<div id="1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque et facilisis elit. Ut interdum, odio et aliquam tempor, felis odio auctor erat, eget elementum lectus arcu tempus elit.</div> 

<div id="2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque et facilisis elit. Ut interdum, odio et aliquam tempor, felis odio auctor erat, eget elementum lectus arcu tempus elit.</div> 

function findPosition(oElement) { 
    if(typeof(oElement.offsetParent) != 'undefined') { 
     for(var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent) { 
     posX += oElement.offsetLeft; posY += oElement.offsetTop; } 
     return [ posX, posY ]; 
    } else { 
     return [ oElement.x, oElement.y ]; 
    } 
} 

function functionThatSetsPosition() { 
var scrolledFromTop = getScrollXY()[1]; 
var topposition, lastone, offsetFromTop, currentverse, firstVerse = 1; 
while(!document.getElementById('vs'+firstVerse) && firstVerse < 10000) { 
    firstVerse++; 
} 
for(var i = firstVerse, onediv; onediv = document.getElementById('vs'+i); i++) { 
    topposition = findPosition(onediv)[1]; 
    offsetFromTop = topposition - scrolledFromTop; 
    if(i == firstVerse && offsetFromTop >= 0) { 

     currentverse = i; 
     break; 
    } 
    if(offsetFromTop >= 0 && offsetFromTop <= 20) { 

     currentverse = i; 
     break; 
    } 
    if(offsetFromTop > 20) { 

     currentverse = lastone; 
     break; 
    } 
    //store this as the last one for checking afterwards 
    lastone = i; 
} 
if(!currentverse) { 
    currentverse = lastone; 
} 
document.getElementById('sayverse').innerHTML = 'Verse '+currentverse; 

}

菲利普

回答

0

我假设你想检测元件的位置来确定第二值(:)后的数字。

如果第二个数字是您的变量称为offsetFromTop,那么它可以被添加像这样:

document.getElementById('sayverse').innerHTML = 'Verse ' + currentverse + ':' + offsetFromTop; 
+0

我想给我的Y坐标为我滚动。我忘了提及id中的数字前缀为'vs'。我包含这段代码,因为它是检测滚动的JS代码的一部分。之前我没有加入,因为我认为没有必要。 '函数findPosition(oElement){ \t如果(typeof运算(oElement.offsetParent)= '未定义'!){ \t \t为(VAR POSX = 0,POSY = 0; oElement; oElement = oElement.offsetParent){ \t \t \t posX + = oElement.offsetLeft; \t \t \t posY + = oElement.offsetTop; \t \t} \t \t return [posX,posY]; \t} else { \t \t return [oElement.x,oElement.y]; \t} }' – 2012-08-02 15:57:45