在滚动条上显示Div ID

时间:2012-08-02 14:51:48

标签: javascript

我有这个JS代码,在弹出框中显示div滚过它时的id值。当id看起来像这样时它工作正常:id =“1”。但是如何更改它以检测看起来像这样的ID:id =“1:1”或id =“23:4”?两个数字用冒号分隔。

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

}

菲利普

1 个答案:

答案 0 :(得分:0)

我假设您正在尝试检测元素的位置以确定第二个值(后面的数字:)。

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

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