简体   繁体   English

如何找到文本的绝对或相对位置或<br />在 HTML 中?

[英]How to find absolute or relative position of text or <br /> in HTML?

I was wondering if there is a way I could find the position of letters in HTML using Javascript or jQuery?我想知道是否有一种方法可以使用 Javascript 或 jQuery 在 HTML 中找到字母的位置? I highly doubt this is possible, but it would make my life so much easier.我非常怀疑这是可能的,但它会让我的生活变得更轻松。

Alternatively, Is there a way to find the position of <br /> tags in HTML using JS?或者,有没有办法使用 JS 在 HTML 中找到<br />标签的位置?

Thanks in advance.提前致谢。

As tdammers mentions, handling all of the details of putting together a process to handle what you're suggesting has many nuances that may have to be addressed, depending on what you're doing.正如 tdammers 所提到的,处理将处理您的建议的流程放在一起的所有细节可能需要解决许多细微差别,具体取决于您在做什么。

The basics of what you're trying to do is:你要做的事情的基础是:

  1. Wrap an element around the text you want to find the position for, ie, in the case of text, probably a <span> .在要查找位置的文本周围包裹一个元素,即,在文本的情况下,可能是<span>
  2. Get either the $.offset() or $.position() of the element or elements you added.获取您添加的一个或多个元素的$.offset()$.position() Whichever you choose is relevant to what you're trying to do;无论您选择哪种方式,都与您尝试做的事情相关; the first is relevant to the document , the second to the containing element.第一个与document相关,第二个与包含元素相关。

I created a simple demo of a script to "highlight" a term typed into a textbox in several paragraphs using div s with position: absolute and top / left offsets relative to the terms found in the paragraphs (located by the <span> surrounding them).我创建了一个简单的脚本演示来“突出显示”在几个段落中使用div s 输入到文本框中的一个术语, position: absolute相对于段落中找到的术语的position: absolutetop / left偏移(位于它们周围的<span> )。

Note, this is only a demonstration (of $.offset() );请注意,这只是一个演示( $.offset() ); it's not production-ready code.它不是生产就绪代码。 There's a link to the live fiddle demo below the code snippets.代码片段下方有一个指向现场小提琴演示的链接。

First, I created a function to find and create a highlight <div> for each term found.首先,我创建了一个函数来查找并为找到的每个术语创建一个突出显示的<div>

function highlightWordPositions(word) {
    var $paras = $('p'),
        $spans,
        _top = 0,
        _left = 0;

    $paras.each(function(){
        var $p = $(this),
            regex = new RegExp(word, 'g');

        $p.html($p.text().replace(regex, '<span>' + word + '</span>'));
        $spans = $p.find('span');

        $spans.each(function(){
            var $span = $(this),
                $offset = $span.offset(),
                $overlay = $('<div class="overlay"/>');

            $overlay
                .offset($offset)
                .css({
                    width: $span.innerWidth(),
                    height: $span.innerHeight()
                }).show();

            $(document.body).append($overlay);
        });
    });
}

Then, I attached a callback to the $.keyup() event:然后,我将回调附加到$.keyup()事件:

$('#term').keyup(function(event){
    var term = this.value;

    if (term == '') {
        $('.overlay').remove();
        return false;
    } else if (term.indexOf(' ') != -1) {
        this.value = term.replace(' ', '');
        return false;
    }

    $('.overlay').remove();

    highlightWordPositions(term);
});

http://jsfiddle.net/JaN75/ http://jsfiddle.net/JaN75/

There is a simpler and more lightweight way (vs other answers that suggest overlays) to find the position of letters in DOM elements: use a range.有一种更简单、更轻量的方法(与其他建议覆盖的答案相比)来查找 DOM 元素中字母的位置:使用范围。

// returns { left, top, etc } in px
function getLetterPositions(myElementWithText, myTextElementIndex, myLetterPosition) {
    var range = document.createRange();
    range.setStart(myElementWithText.childNodes[myTextElementIndex], myLetterPosition);
    range.setEnd(myElementWithText.childNodes[myTextElementIndex], myLetterPosition+1);
    return range.getBoundingClientRect();
}
  • the element with the text holding the target letter is myElementWithText (eg a <div> )包含目标字母文本的元素是myElementWithText (例如<div>
  • the element child with the text (ie the textNode ) is at index myTextElementIndex (in most cases, 0)带有文本的元素子元素(即textNode )位于索引myTextElementIndex (在大多数情况下,0)
  • the position of the letter you are trying to find is myLetterPosition (eg if text is "abcd" and you want "c" , this will be 2)您要查找的字母的位置是myLetterPosition (例如,如果文本是"abcd"并且您想要"c" ,这将是 2)

Assuming that you mean the position where the character is displayed on screen, in pixels:假设您的意思是字符在屏幕上显示的位置,以像素为单位:

jQuery or the DOM do not model individual characters in their object models, so you can't read a character's position directly. jQuery 或 DOM 不会在其对象模型中对单个字符进行建模,因此您无法直接读取字符的位置。

The best way I can think of is to insert a dummy element right before (or after) the character, eg a zero-width span with a special class, and then get its position.我能想到的最好方法是在字符之前(或之后)插入一个虚拟元素,例如具有特殊类的零宽度跨度,然后获取其位置。 Alternatively, you can wrap the character in such a special element, and then get the wrapper's position, width, height, etc.或者,您可以将字符包裹在这样一个特殊的元素中,然后获取包裹的位置、宽度、高度等。

It's still not trivial, because you need to scan the HTML, and you don't want to break the HTML by inserting tags where they don't belong - for example, if you want to match the character 'd', you don't want to turn <div> into <<span class="magic">d</span>iv> , as that wouldn't be well-formed HTML.这仍然不是微不足道的,因为您需要扫描 HTML,并且您不想通过在不属于它们的位置插入标签来破坏 HTML - 例如,如果您想匹配字符 'd',则不需要'不想将<div>变成<<span class="magic">d</span>iv> ,因为这不是格式良好的 HTML。

Also, inserting those dummy elements may alter the layout slightly, depending on how the browser handles kerning.此外,插入这些虚拟元素可能会稍微改变布局,具体取决于浏览器如何处理字距调整。

in action: http://jsfiddle.net/WKgWM/在行动: http : //jsfiddle.net/WKgWM/

html: html:

<p>Percussus ait in fuerat construeret cena reges undis effugere quod una.</p>​

js: js:

var selection = "dis";
var spn = '<span class="selected">'+selection+'</span>';
$("p").html($("p").html().replace(selection,spn));

css: css:

.selected{
  background-color:#FF00FF;
}​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM