开发者

Find specific text in a DIV according to offset in pixels

开发者 https://www.devze.com 2022-12-11 00:53 出处:网络
I want to insert an image tag into a block of text so that the image is, say, 100 pixels down in the DIV.

I want to insert an image tag into a block of text so that the image is, say, 100 pixels down in the DIV.

    <div>
    A lot of text in a text block and a <img tag> somewhere
that is floated left or right and positioned inside the text block
    </div>

So, the tag above is put in the text block to be floated so that it is positioned at 100px DOWN in the DIV. Now, this can't be done statically, it has to be done in javascript since 100px down in the div may be represented by different text depending on font rendering issues and such.

So, is there a way to fin开发者_StackOverflow中文版d what "word" in a text block that is 100px down in the DIV? jQuery perhaps?


The short answer is no

Basically it comes down to the DOM doesn't give a way for you to get an elements pixel position. There are sort of hacks you can do for some browsers, but good luck getting a solution working.

If you cannot get the position of the containing div, you are not going to get the position for the text within.

Leaving aside the no, if you were to find a way to get the div's pixel height, I would follow a procedure similar to the following.

  1. Get the text from inside the div and store it in a local var.
    1. Inside a loop for each word in the text:
    2. Insert a div tag into just before the word.
    3. Get the pixel position of the div tag.
    4. Use this to determine the closest word to pixel pos 100 down.
  2. Once you have the closest position, create a document fragment to build up your new inner for the div
  3. Replace the div's content with the document fragment.
0

精彩评论

暂无评论...
验证码 换一张
取 消