通过scrollOffset查找最接近的锚点href

时间:2012-05-17 19:53:31

标签: javascript uiwebview anchor

我有一个UIWebView,其中HTML页面已完全加载。 UIWebView的框架为320 x 480并水平滚动。我可以获得用户当前所在的当前偏移量。我想使用XY偏移找到最近的锚点,这样我就可以“跳转到”锚定位置。这是可能吗?有人可以指点我使用Javascript中的资源来执行此操作吗?

<a id="p-1">Text Text Text Text Text Text Text Text Text<a id="p-2">Text Text Text Text Text Text Text Text Text ... 

更新

我超级难过的JS代码:

function posForElement(e)
{
    var totalOffsetY = 0;

    do
    {
        totalOffsetY += e.offsetTop;
    } while(e = e.offsetParent)

    return totalOffsetY;
}

function getClosestAnchor(locationX, locationY)
{
    var a = document.getElementsByTagName('a');

    var currentAnchor;
    for (var idx = 0; idx < a.length; ++idx)
    {
        if(a[idx].getAttribute('id') && a[idx+1])
        {
            if(posForElement(a[idx]) <= locationX && locationX <= posForElement(a[idx+1])) 
            {
                currentAnchor = a[idx];
                break;
            }
            else
            {
                currentAnchor = a[0];
            }
        }
    }

    return currentAnchor.getAttribute('id');
}

目标-C

float pageOffset = 320.0f;

NSString *path = [[NSBundle mainBundle] pathForResource:@"GetAnchorPos" ofType:@"js"];
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[webView stringByEvaluatingJavaScriptFromString:jsCode];

NSString *execute = [NSString stringWithFormat:@"getClosestAnchor('%f', '0')", pageOffset];
NSString *anchorID = [webView stringByEvaluatingJavaScriptFromString:execute];

4 个答案:

答案 0 :(得分:9)

[UPDATE] 我重写了代码以匹配所有具有id的锚点,并简化了sortByDistance函数中向量范数的比较。

检查我的尝试on jsFiddle(前一个是here)。

javascript部分:

// findPos : courtesy of @ppk - see http://www.quirksmode.org/js/findpos.html
var findPos = function(obj) {
    var curleft = 0,
        curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft;
        curtop = obj.offsetTop;
        while ((obj = obj.offsetParent)) {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        }
    }
    return [curleft, curtop];
};

var findClosestAnchor = function (anchors) {

    var sortByDistance = function(element1, element2) {

        var pos1 = findPos( element1 ),
            pos2 = findPos( element2 );

        // vect1 & vect2 represent 2d vectors going from the top left extremity of each element to the point positionned at the scrolled offset of the window
        var vect1 = [
                window.scrollX - pos1[0],
                window.scrollY - pos1[1]
            ],
            vect2 = [
                window.scrollX - pos2[0],
                window.scrollY - pos2[1]
            ];

        // we compare the length of the vectors using only the sum of their components squared
        // no need to find the magnitude of each (this was inspired by Mageek’s answer)
        var sqDist1 = vect1[0] * vect1[0] + vect1[1] * vect1[1],
            sqDist2 = vect2[0] * vect2[0] + vect2[1] * vect2[1];

        if ( sqDist1 <  sqDist2 ) return -1;
        else if ( sqDist1 >  sqDist2 ) return 1;
        else return 0;
    };

    // Convert the nodelist to an array, then returns the first item of the elements sorted by distance
    return Array.prototype.slice.call( anchors ).sort( sortByDistance )[0];
};

当dom准备就绪时,您可以像这样检索和缓存锚点:var anchors = document.body.querySelectorAll('a[id]');

我还没有在智能手机上测试它,但我没有看到任何原因导致它不起作用。 Here是我使用var foo = function() {};表单(more javascript patterns)。

的原因

return Array.prototype.slice.call( anchors ).sort( sortByDistance )[0];行实际上有点棘手。

document.body.querySelectorAll('a['id']')返回一个NodeList,其中包含当前页面正文中具有属性“id”的所有锚点。 遗憾的是,NodeList对象没有“sort”方法,并且无法使用Array原型的sort方法,as it is with some other methods, such as filter or mapNodeList.prototype.sort = Array.prototype.sort本来不错)

This article更好地解释了为什么我使用Array.prototype.slice.call将我的NodeList转换为数组。

最后,我使用Array.prototype.sort方法(以及自定义sortByDistance函数)来比较NodeList的每个元素,并且我只返回第一个项目,这是最接近的之一。

要查找使用固定定位的元素的位置,可以使用此findPos的更新版本:http://www.greywyvern.com/?post=331

我的答案可能不是更有效率(drdigit必须比我的更多)但我更喜欢简单而不是效率,我认为这是最容易维持的。

[再次更新]

这是一个经过大量修改的findPos版本,适用于webkit css列(没有间隙):

// Also adapted from PPK - this guy is everywhere ! - check http://www.quirksmode.org/dom/getstyles.html
var getStyle = function(el,styleProp)
{
    if (el.currentStyle)
        var y = el.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
    return y;
}

// findPos : original by @ppk - see http://www.quirksmode.org/js/findpos.html
// made recursive and transformed to returns the corect position when css columns are used

var findPos = function( obj, childCoords ) {
   if ( typeof childCoords == 'undefined'  ) {
       childCoords = [0, 0];
   }

   var parentColumnWidth,
       parentHeight;

   var curleft, curtop;

   if( obj.offsetParent && ( parentColumnWidth = parseInt( getStyle( obj.offsetParent, '-webkit-column-width' ) ) ) ) {
       parentHeight = parseInt( getStyle( obj.offsetParent, 'height' ) );
       curtop = obj.offsetTop;
       column = Math.ceil( curtop / parentHeight );
       curleft = ( ( column - 1 ) * parentColumnWidth ) + ( obj.offsetLeft % parentColumnWidth );
       curtop %= parentHeight;
   }
   else {
       curleft = obj.offsetLeft;
       curtop = obj.offsetTop;
   }

   curleft += childCoords[0];
   curtop += childCoords[1];

   if( obj.offsetParent ) {
       var coords = findPos( obj.offsetParent, [curleft, curtop] );
       curleft = coords[0];
       curtop = coords[1];
   }
   return [curleft, curtop];
}

答案 1 :(得分:3)

我找到了一种方法来制作它,而不使用scrollOffset。它有点复杂,所以如果你有任何问题要理解它只是评论。

HTML:

<body>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<a />Text Text Text Text Text Text Text Text Text
<br /><br /><br /><br /><br />
<a />Text Text Text Text Text Text Text Text Text
</body>

CSS:

body
{
    height:3000px;
}

JS:

var tempY;

function getClosestAnchor(e)
{
    if((window.event?event.keyCode:e.which)!=97)return;
    var allAnchors=document.getElementsByTagName("a");
    var allDiff=[];
    for(var a=0;a<allAnchors.length;a++)allDiff[a]=margeY(allAnchors[a])-tempY;
    var smallest=allDiff[0];
    for(var a=1;a<allDiff.length;a++)
    {
        if(Math.abs(smallest)>Math.abs(allDiff[a]))
        {
            smallest=allDiff[a];
        }
    }
    window.scrollBy(0,smallest);
}

function margeY(obj)
{
    var posY=0;
    if(!obj.offsetParent)return;
    do posY+=obj.offsetTop;
    while(obj=obj.offsetParent);
    return posY;
}

function update(e)
{
    if(e.pageY)tempY=e.pageY;
    else tempY=e.clientY+(document.documentElement.scrollTop||document.body.scrollTop)-document.documentElement.clientTop;
}


window.onkeypress=getClosestAnchor;
window.onmousemove=update;

这是一个小提琴演示:http://jsfiddle.net/jswuC/

加分:您无需为所有定位器指定ID。

答案 2 :(得分:1)

唷!我说完了!

JS:

var x=0,y=0;//Here are the given X and Y, you can change them
var idClosest;//Id of the nearest anchor
var smallestIndex;
var couplesXY=[];
var allAnchors;
var html=document.getElementsByTagName("html")[0];
html.style.width="3000px";//You can change 3000, it's to make the possibility of horizontal scroll
html.style.height="3000px";//Here too

function random(min,max)
{
    var nb=min+(max+1-min)*Math.random();
    return Math.floor(nb);
}
function left(obj)//A remixed function of this site http://www.quirksmode.org/js/findpos.html
{
    if(obj.style.position=="absolute")return parseInt(obj.style.left);
    var posX=0;
    if(!obj.offsetParent)return;
    do posX+=obj.offsetLeft;
    while(obj=obj.offsetParent);
    return posX;
}
function top(obj)
{
    if(obj.style.position=="absolute")return parseInt(obj.style.top);
    var posY=0;
    if(!obj.offsetParent)return;
    do posY+=obj.offsetTop;
    while(obj=obj.offsetParent);
    return posY;
}

function generateRandomAnchors()//Just for the exemple, you can delete the function if you have already anchors
{
    for(var a=0;a<50;a++)//You can change 50
    {
        var anchor=document.createElement("a");
        anchor.style.position="absolute";
        anchor.style.width=random(0,100)+"px";//You can change 100
        anchor.style.height=random(0,100)+"px";//You can change 100
        anchor.style.left=random(0,3000-parseInt(anchor.style.width))+"px";//If you changed 3000 from
        anchor.style.top=random(0,3000-parseInt(anchor.style.height))+"px";//the top, change it here
        anchor.style.backgroundColor="black";
        anchor.id="Anchor"+a;
        document.body.appendChild(anchor);
    }
}
function getAllAnchors()
{
    allAnchors=document.getElementsByTagName("a");
    for(var a=0;a<allAnchors.length;a++)
    {
        couplesXY[a]=[];
        couplesXY[a][0]=left(allAnchors[a]);
        couplesXY[a][1]=top(allAnchors[a]);
    }
}
function findClosestAnchor()
{
    var distances=[];
    for(var a=0;a<couplesXY.length;a++)distances.push(Math.pow((x-couplesXY[a][0]),2)+Math.pow((y-couplesXY[a][1]),2));//Math formula to get the distance from A to B (http://euler.ac-versailles.fr/baseeuler/lexique/notion.jsp?id=122). I removed the square root not to slow down the calculations
    var smallest=distances[0];
    smallestIndex=0;
    for(var a=1;a<distances.length;a++)if(smallest>distances[a])
    {
        smallest=distances[a];
        smallestIndex=a;
    }
    idClosest=allAnchors[smallestIndex].id;
    alert(idClosest);
}
function jumpToIt()
{
    window.scrollTo(couplesXY[smallestIndex][0],couplesXY[smallestIndex][1]);
    allAnchors[smallestIndex].style.backgroundColor="red";//Color it to see it
}

generateRandomAnchors();
getAllAnchors();
findClosestAnchor();
jumpToIt();

小提琴:http://jsfiddle.net/W8LBs/2

PS:如果你在智能手机上打开这个小提琴,它不起作用(我不知道为什么),但是如果你在智能手机上的样本中复制这段代码,它就可以了(但是你必须指定{{ 1}}和<html>部分。)

答案 3 :(得分:0)

这个答案没有得到足够的重视。

完成示例,快速(二进制搜索)并缓存位置。

固定高度和宽度,最近锚点和scrollto的id

<!DOCTYPE html>
<html lang="en">
<head>
<meta>
<title>Offset 2</title>
<style>
body { font-family:helvetica,arial; font-size:12px; }
</style>
<script>
var ui = reqX = reqY = null, etop = eleft = 0, ref, cache;
function createAnchors()
{
    if (!ui)
    {
        ui = document.getElementById('UIWebView');
        reqX = document.getElementById('reqX');
        reqY = document.getElementById('reqY');
        var h=[], i=0;
        while (i < 1000)
            h.push('<a>fake anchor ... ',i,'</a> <a href=#>text for anchor <b>',(i++),'</b></a> ');
        ui.innerHTML = '<div style="padding:10px;width:700px">' + h.join('') + '</div>';
        cache = [];
        ref = Array.prototype.slice.call(ui.getElementsByTagName('a'));
        i = ref.length;
        while (--i >= 0)
        if (ref[i].href.length == 0)
            ref.splice(i,1);
    }
}
function pos(i)
{
    if (!cache[i])
    {
        etop = eleft = 0;
        var e=ref[i];
        if (e.offsetParent)
        {
            do
            {
                etop += e.offsetTop;
                eleft += e.offsetLeft;
            } while ((e = e.offsetParent) && e != ui)
        }
        cache[i] = [etop, eleft];       
    }
    else
    {
        etop = cache[i][0];
        eleft = cache[i][1];
    }
}
function find()
{
    createAnchors();
    if (!/^\d+$/.test(reqX.value))
    {
        alert ('I need a number for X');
        return;
    }   
    if (!/^\d+$/.test(reqY.value))
    {
        alert ('I need a number for Y');
        return;
    }
    var
        x = reqX.value,
        y = reqY.value,
        low = 0,
        hi = ref.length + 1, 
        med,
        limit = (ui.scrollHeight > ui.offsetHeight) ? ui.scrollHeight - ui.offsetHeight : ui.offsetHeight - ui.scrollHeight;
    if (y > limit)
        y = limit;
    if (x > ui.scrollWidth)
        x = (ui.scrollWidth > ui.offsetWidth) ? ui.scrollWidth : ui.offsetWidth;
    while (low < hi)
    {
        med = (low + ((hi - low) >> 1));
        pos(med);
        if (etop == y)
        {
            low = med;
            break;
        }
        if (etop < y)
            low = med + 1;
        else
            hi = med - 1;
    }
    var ctop = etop;
    if (eleft != x)
    {
        if (eleft > x)
            while (low > 0)
            {
                pos(--low);
                if (etop < ctop || eleft < x)
                {
                    pos(++low);
                    break;
                }
            }
        else
        {
            hi = ref.length;
            while (low < hi)
            {
                pos(++low);
                if (etop > ctop || eleft > x)
                {
                    pos(--low);
                    break;
                }
            }
        }
    }
    ui.scrollTop = etop - ui.offsetTop;
    ui.scrollLeft = eleft - ui.offsetLeft;
    ref[low].style.backgroundColor = '#ff0';
    alert(
        'Requested position: ' + x + ', ' + y + 
        '\nScrollTo position: ' + ui.scrollLeft + ', '+ ui.scrollTop + 
        '\nClosest anchor id: ' + low
        );
}
</script>
</head>
<body>
<div id=UIWebView style="width:320px;height:480px;overflow:auto;border:solid 1px #000"></div>
<label for="req">X: <input id=reqX type=text size=5 maxlength=5 value=200></label>
<label for="req">Y: <input id=reqY type=text size=5 maxlength=5 value=300></label>
<input type=button value="Find closest anchor" onclick="find()">
</body>
</html>