选择文本,然后用Javascript计算它与顶部的距离? [英] Select text and then calculate its distance from top with Javascript?

查看:111
本文介绍了选择文本,然后用Javascript计算它与顶部的距离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用JavaScript在网页上查找给定的文本字符串,然后从页面顶部计算其距离(以像素为单位)?如果是这样,我们将不胜感激。

Is it possible with JavaScript to find a given string of text on a webpage, and then calculate its distance (in pixels) from the top of the page? If so, an example would be appreciated.

推荐答案

更新:更加强大。

一个有趣和互动的演示:
看到它的实际效果,这里

A fun and interactive demo: See it in action, here.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<head>
    <title>Word Finder Fun</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
        body {
            font-size:          16px;
            font-weight:        normal;
            font-family:        "Trebuchet MS", Helvetica, Tahoma, Arial, sans-serif;
            padding:            10px 5%;
            line-height:        1.5;
            min-width:          680px;
        }
        table {
            border:             1px solid black;
            border-collapse:    collapse;
            margin:             1em;
        }
        th, td {
            margin:             0px;
            padding:            0.5ex;
            border:             1px solid black;
        }
        td {
            min-width:          8em;
        }
        th {
            font-weight:        bold;
            background:         wheat;
            text-align:         right;
        }
        caption {
            margin:             0;
            font-size:          1.2em;
            font-style:         italic;
            text-align:         left;
            caption-side:       top;
        }
        form {
            float:              left;
            margin:             2.5em 5em;
        }
        label {
            font-weight:        bold;
            background:         yellow;
        }
        input {
            padding:            0.5ex;
        }
        .FoundText {
            background:         red;
            margin:             0;
            padding:            0;
        }
    </style>


    <!-- jQuery is required. -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>

    <script type="text/javascript">
        function jQueryMain ()
        {
            $("#idSearchStr").focus ();             //-- User convenience, set focus to search input.

            $("button").click (SearchPageText);     //-- On button click, search away.

            $("#idForm1").submit (SearchPageText);  //-- Intercept form submit (enter key too).
        }


        function SearchPageText (zEvent)
        {
            /*--- Kill any old spans (otherwise they might interfere with new search).
            */
            var NastyOldSpans        = $("span.FoundText");

            NastyOldSpans.each (function () {var X = $(this);  X.before (X[0].innerHTML); });
            NastyOldSpans.remove();


            var SearchStr           = $("#idSearchStr")[0].value;

            //--- Ignore empty or trivial searches.
            if (!SearchStr  ||  /^\s+$/.test (SearchStr) )
                return false;

            var zAllnodes           = $("body *");
            var iNumNodes           = zAllnodes.length;
            var zRegEx              = new RegExp ('(' + SearchStr + ')', 'ig');
            var bFoundOne           = false;


            /*--- Look for string and wrap it in a span if found.
            */
            for (J=0;  J < iNumNodes;  J++)
            {
                /*-- Get node text in a way that supports both IE and Decent browsers.
                    We do NOT want to use innerHTML here.  We do not want to mess
                    with matches in HTML tags, for now.
                */
                var zNode           = $(zAllnodes[J]);
                var sNodeTxt        = (zAllnodes[J]).innerText  ||  (zAllnodes[J]).textContent;


                if (zRegEx.test (sNodeTxt) )
                {
                    var OldStr      = (zAllnodes[J]).innerHTML;
                    var NewStr      = OldStr.replace (zRegEx, '<span class="FoundText">$1<\/span>');

                    //--- We want only "leaf" nodes (contain no html).  So, if we detect a tag, skip.
                    if (/[<>]/.test (OldStr) )
                        continue;

                    //--- SET with innerHTML, so that new span will take.
                    (zAllnodes[J]).innerHTML    = NewStr;

                    bFoundOne       = true;
                }
            }


            /*--- Grab the string's particulars and update the status table.
            */
            var iNumMatchChars      = 0;
            var iTop                = 'na';
            var iLeft               = 'na';

            if (bFoundOne)
            {
                iNumMatchChars      = SearchStr.length;
                var aStrPosition    = $("span.FoundText:first").offset ();
                iTop                = aStrPosition.top;
                iLeft               = aStrPosition.left;
            }

            var zStatusTable        = $("#idStatTable")[0];
            zStatusTable.rows[0].cells[1].innerHTML = iTop;
            zStatusTable.rows[1].cells[1].innerHTML = iLeft;
            zStatusTable.rows[2].cells[1].innerHTML = iNumMatchChars;

            return false;   //-- Stop form submit
        }


        $(document).ready (jQueryMain);
    </script>
</head>

<body>
    <form id="idForm1" method="post" action="">
    <p>
        <label for="idSearchStr">Enter Search String: </label><input type="text" id="idSearchStr"><br>
        <button type="button">Find in page</button>
    </p>
    </form>

    <table id="idStatTable" summary="Search match results">
        <caption>First Match:</caption>
        <tr>
            <th>Top:</th>
            <td></td>
        </tr>
        <tr>
            <th>Left:</th>
            <td></td>
        </tr>
        <tr>
            <th>Char cnt:</th>
            <td></td>
        </tr>
    </table>

    <p>
        I never spend much time in school but I taught ladies plenty. It's true I hire my body out
        for pay, hey hey. I've gotten burned over Cheryl Tiegs, blown up for Raquel Welch. But when
        I end up in the hay it's only hay, hey hey. I might jump an open drawbridge, or Tarzan from
        a vine. 'Cause I'm the unknown stuntman that makes Eastwood look so fine.
    </p>
    <p>
        Hey there where ya goin', not exactly knowin', who says you have to call just one place
        home. He's goin' everywhere, B.J. McKay and his best friend Bear. He just keeps on movin',
        ladies keep improvin', every day is better than the last. New dreams and better scenes, and
        best of all I don't pay property tax. Rollin' down to Dallas, who's providin' my palace, off
        to New Orleans or who knows where. Places new and ladies, too, I'm B.J. McKay and this is my
        best friend Bear.
    </p>
    <p>
        Top Cat! The most effectual Top Cat! Who's intellectual close friends get to call him T.C.,
        providing it's with dignity. Top Cat! The indisputable leader of the gang. He's the boss,
        he's a pip, he's the championship. He's the most tip top, Top Cat.
    </p>
    <p>
        This is my boss, Jonathan Hart, a self-made millionaire, he's quite a guy. This is Mrs H.,
        she's gorgeous, she's one lady who knows how to take care of herself. By the way, my name is
        Max. I take care of both of them, which ain't easy, 'cause when they met it was MURDER!
    </p>
    <p>
        Mutley, you snickering, floppy eared hound. When courage is needed, you're never around.
        Those medals you wear on your moth-eaten chest should be there for bungling at which you are
        best. So, stop that pigeon, stop that pigeon, stop that pigeon, stop that pigeon, stop that
        pigeon, stop that pigeon, stop that pigeon. Howwww! Nab him, jab him, tab him, grab him,
        stop that pigeon now.
    </p>
</body>
</html>

这篇关于选择文本,然后用Javascript计算它与顶部的距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆