JavaScript是否可以在網頁上查找給定的文本字符串,然後計算頁面頂部的距離(以像素爲單位)?如果是這樣,一個例子將不勝感激。選擇文本,然後用Javascript計算它從頂部的距離?
回答
更新:更加堅固。
一個有趣的互動演示: 看到它的行動,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>
這是一個有趣的想法。無論如何,我建立了一個迷你班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, "<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)
希望這是有道理的 - 這是粗糙的,但應該給你一些想法。如果您通過鼠標使用此選項,則它會比搜索更容易。此外,請記住,這將搜索HTML,因此做一個a very good year
與a very <a href=''>good</a> year
標記的查找將失敗(您可以查詢文本屬性代替)。
它使用array.some(),它會在第一次匹配後停止循環。如果你想找到多個實例,你需要重構。
好運
似乎不適用於真正的HTML頁面。 – user379588 2010-07-05 01:45:26
它搜索整個身體的字符串,增加了一類發現並提醒每個元素的座標。
不幸的是,我沒有看到其他帖子,但這個稍微短一些。
$(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);
});
}
而且有些lipsum文本搜索
<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>
感謝您的代碼,但是,當我在FireFox中運行一個測試時,它在一個頁面上有更多的內容,它在60-80像素左右。 – user379588 2010-07-03 22:42:20
我假設你從頂部/左側座標進行測量。我可能會玩一玩,看看發生了什麼。或者您是否已經找到了解決方案? – Marko 2010-07-05 05:30:28
從選定的文本到頂部。 – user379588 2010-07-07 05:59:28
- 1. 我如何計算從pictureBox1的頂部到form1的頂部的距離?
- 2. 選擇幾個項目,然後將它們之間的距離
- 3. 計算距離google距離計算器的距離,然後與數字相乘但
- 4. 計算行總數與選擇全部然後計算大小
- 5. 距離成本計算器
- 6. 計算距離
- 7. 計算距離
- 8. 距離計算
- 9. 計算距離
- 10. 計算距離
- 11. 計算距離
- 12. 計算距離
- 13. 計算距離
- 14. 計算距離
- 15. 計算距離
- 16. 計算距離
- 17. 計算距離
- 18. 從距離計算經度
- 19. 計算用戶從頁面頂部或頁面左側滾動的距離
- 20. 使用javascript確定從div頂部到窗口頂部的距離
- 21. 如何計算當前從頂部選擇的選項?
- 22. 計算距離位置的距離 - iPhone
- 23. 如何計算距離cellID的距離?
- 24. 的Javascript距離計算返回NaN
- 25. 選擇所有文本,然後複製它在javascript
- 26. 計算3d旋轉後的y距離?
- 27. 滾動頂部,然後底部,然後頂部,然後底部
- 28. 計算距離CoreLocation
- 29. Matlab計算距離
- 30. PostGis距離計算
這在演示中很安靜。我爲你提供一個整潔的例子感到受寵若驚。我要在基本的HTML頁面上測試它。 – user379588 2010-07-03 22:48:19
@subwayxpress:謝謝。請注意,我只是調整它,以確保HTML標籤不匹配。 – 2010-07-03 23:42:38