0

我有这个 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;

}

菲利普

4

1 回答 1

0

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

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

document.getElementById('sayverse').innerHTML = 'Verse ' + currentverse + ':' + offsetFromTop;
于 2012-08-02T15:22:07.547 回答