È possibile con JavaScript trovare una determinata stringa di testo in una pagina Web e quindi calcolare la sua distanza (in pixel) dalla parte superiore della pagina? Se è così, un esempio sarebbe apprezzato.Seleziona il testo e poi calcola la sua distanza dall'alto con Javascript?
risposta
Update: reso più robusto.
Una demo divertente e interattiva: Guardalo in azione, 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>
questa è un'idea divertente. comunque, ho costruito una mini-classe in mootools che funziona un po '. Devo ancora provarlo in un layout di pagina più complesso ma la premessa è, trovare tutti gli elementi con innerHTML che possono essere utili, scansionare il testo per una corrispondenza, se trovato, clonare l'elemento genitore mentre si sostituisce il testo con una span, quindi recuperando gli offset dello span dall'alto/a sinistra ecc. NON modificherà l'HTML dell'elemento esistente ed è scalabile.
il risultato è qui: http://www.jsfiddle.net/dimitar/eBPFb/
e la fonte è questa:
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, "<span id='posText'>"+text+"</span>")
}).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)
speranza questo ha un senso - è dura, ma dovrebbe darvi alcune idee. se usi una selezione per questo tramite il mouse, diventa molto più facile della ricerca. Inoltre, tieni presente che questa ricerca in html, quindi facendo una ricerca per a very good year
con il markup di a very <a href=''>good</a> year
avrà esito negativo (puoi invece interrogare le proprietà del testo).
utilizza array.some() che interrompe il ciclo dopo la prima corrispondenza. se vuoi trovare più istanze, devi refactoring.
buona fortuna
Sembra non funzionare su una vera pagina HTML. – user379588
Si cerca tutto il corpo di una stringa, aggiunge una classe di trovate e avvisi le coordinate per ogni elemento.
Purtroppo non ho visto l'altro post, ma questo è leggermente più corto.
$(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, '<span class="found">' + text + '</span>');
$(this).html(replacedText);
});
$("span.found").each(function() {
var offset = $(this).offset();
alert("top: " + offset.top + "\n left: " + offset.left);
});
}
e del testo lipsum per la ricerca di
<div id="wrapper">
<p>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. </p>
<p>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. </p>
<p>Nulla cursus, metus ut consequat adipiscing, elit nisi semper mi, at commodo orci sapien ullamcorper lorem. Quisque scelerisque felis ut felis ultrices pellentesque. </p>
</div>
Grazie per il codice, tuttavia, quando eseguo un test in FireFox, su una pagina con un po 'più di contenuto, è spento di circa 60-80 pixel. – user379588
Suppongo che tu stia misurando dalla coordinata superiore/sinistra. Potrei avere un gioco in giro e vedere cosa sta succedendo .. O hai già trovato una soluzione? – Marko
Dal testo selezionato in alto. – user379588
- 1. Google Maps calcola la distanza errata?
- 2. Calcola la distanza tra due puntatori grezzi
- 3. Seleziona testo in javascript
- 4. Calcola la distanza dalla linea smussata
- 5. Calcola la distanza dalla caratteristica più vicina con le Geopandas
- 6. Calcola distanza geo in elasticsearch
- 7. Come posso stampare qualcosa e poi la sua lista?
- 8. Calcola la distanza tra il dispositivo Bluetooth in Android
- 9. Calcola la differenza di orario con JavaScript
- 10. Calcola la distanza tra i punti nelle tabelle di fusione
- 11. Calcola "in linea d'aria" distanza php
- 12. SELEZIONARE CASO QUANDO POI (SELEZIONA)
- 13. Calcola la distanza in (x, y) tra due punti GPS
- 14. Calcola la distanza tra due coordinate x/y?
- 15. Come si calcola la distanza di modifica dell'albero?
- 16. È possibile misurare la distanza rispetto all'oggetto con la fotocamera?
- 17. Aumentare la distanza tra testo e titolo sull'asse Y
- 18. R: Calcola la distanza del coseno da una matrice di termini e documenti con tm e proxy
- 19. seleziona l'elemento di testo HTML con regex?
- 20. UISearchBar seleziona tutto il testo
- 21. Seleziona record da un database SQL Server utilizzando la geografia e la distanza
- 22. JavaScript: capire il punto Y da angolo e distanza
- 23. JavaScript AJAX logger a distanza
- 24. JQuery seleziona per testo interno
- 25. usa javascript per trovare il parametro in url e poi applica se poi logico
- 26. Come si calcola la distanza tra due punti di latitudine e longitudine?
- 27. Jsoup seleziona il testo dopo il tag
- 28. Calcola efficientemente la media e la mediana
- 29. Seleziona nodo di testo con i CSS
- 30. C# seleziona il testo da messagebox.show popup
Questo è silenzioso nella demo. Ero lusingato che tu fornissi un esempio chiaro. Lo testerò su una pagina HTML di base. – user379588
@subwayxpress: Grazie. Si noti che l'ho appena ottimizzato per garantire che i tag HTML non corrispondessero. –