选择文本,然后用Javascript计算它与顶部的距离?

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

更新:更加强大。

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

   Word Finder Fun        


First Match:
Top:
Left:
Char cnt:

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.

Hey there where ya goin', not exactly knowin', who says you have to call just one place home. He's goin' everywhere, BJ 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 BJ McKay and this is my best friend Bear.

Top Cat! The most effectual Top Cat! Who's intellectual close friends get to call him TC, 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.

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!

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.

它在整个主体中搜索一个字符串,添加一个找到的类并提醒每个元素的坐标。

不幸的是,我没有看到另一篇文章,但这篇文章略短。

 $(document).ready(function() { findText("commodo"); }); function findText(text) { var $matchedEl = $('body:contains(' + text + ')'); var replacedText; var re = new RegExp(text, 'ig'); $matchedEl.each(function() { replacedText = $(this).html().replace(re, '' + text + ''); $(this).html(replacedText); }); $("span.found").each(function() { var offset = $(this).offset(); alert( "top: " + offset.top + "\n left: " + offset.left); }); } 

还有一些嘴唇文字要搜索

 

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum tincidunt cursus tortor, ut mollis nulla commodo non. Quisque libero mauris, ullamcorper a porttitor nec, blandit eu sem. Vestibulum ac libero mauris, in tincidunt sem. Sed aliquet porta neque ut scelerisque. Aliquam nec aliquam ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse potenti. Duis ut molestie ante.

Vestibulum ac odio id tortor interdum pharetra sit amet at nunc. Praesent pellentesque justo non massa vulputate vitae consectetur augue venenatis. Cras semper nulla tincidunt dolor sagittis sodales. Aenean malesuada eleifend enim nec accumsan. Morbi ut neque metus. Aenean erat ligula, sagittis vel scelerisque et, placerat vel diam. Nunc hendrerit quam at turpis ultrices imperdiet. Suspendisse sit amet mi sed enim ultrices consectetur. Quisque eu lobortis massa.

Nulla cursus, metus ut consequat adipiscing, elit nisi semper mi, at commodo orci sapien ullamcorper lorem. Quisque scelerisque felis ut felis ultrices pellentesque.

这是一个有趣的想法。 无论如何,我在mootools中建造了一个小型的,在某种程度上有效。 我还没有在更复杂的页面布局中测试它,但前提是,找到可能有用的innerHTML的所有元素,扫描文本以获得匹配,如果找到,克隆父元素同时用span替换文本,然后从顶部/左侧检索跨度的偏移等。这不会修改现有元素的HTML并且是可伸缩的。

结果如下: http : //www.jsfiddle.net/dimitar/eBPFb/

而来源是这样的:

 var getTextOffset = new Class({ Implements: [Options], options: { selector: "*", // all elements filter: "innerHTML", // only those that have this property are worth lookign at skip: ["link", "style", "script","head","html","meta","input","textarea","select","body"] // useless tags we don't care about }, initialize: function(text, options) { this.setOptions(options); if (!text) return; // nothing to do. this.elements = document.getElements(this.options.selector).filter(function(el) { return this.options.filter in el && !this.options.skip.contains(el.get("tag")); }, this); if (!this.elements.length) return; return this.findText(text); }, findText: function(text) { var coords = false; this.elements.some(function(el) { var eltext = el.get("html"); if (eltext.contains(text)) { var c = el.getCoordinates(); var clone = new Element("div", { "class": "clone", styles: c, html: eltext.replace(text, ""+text+"") }).inject(document.body, "top"); coords = document.id("posText").getCoordinates(); clone.destroy(); } }); return coords; } }); var pleistoscene = new getTextOffset("Pleistocene"); if (pleistoscene) // found text so highlight it new Element("div", { styles: $merge(pleistoscene, { position: "absolute", background: "yellow" }), opacity: .7, title: pleistoscene.top + "px top" }).inject(document.body); // mouseover the yelow element to see offset (pleitoscene.top) 

希望这是有道理的 – 这很粗糙,但应该给你一些想法。 如果您通过鼠标使用选择,它会比搜索更容易。 另外,请记住,这会搜索html,因此找到a very good year ,以及a very good year标记将失败(您可以查询文本属性)。

它使用的是array.some(),它将在第一次匹配后停止循环。 如果要查找多个实例,则需要重构。

祝好运