使用JavaScript / jQuery根据突出显示的文本返回CSS选择器列表

时间:2022-11-13 18:41:03

I've been given some project requirements that involve (ideally) returning a list of CSS selectors based on highlighted text.

我已经获得了一些项目需求,这些需求涉及(理想情况下)基于突出显示的文本返回CSS选择器列表。

In other words, a user could do something like this on a page:

换句话说,用户可以在页面上执行以下操作:

  • Click a button to indicate that their next text selection should be recorded.
  • 单击按钮以指示应记录下一个文本选择。
  • Highlight some text on the page.
  • 突出显示页面上的一些文字。
  • See a generated list of CSS selectors that correspond to all the elements that contain the highlighted text.
  • 查看生成的CSS选择器列表,该列表对应于包含突出显示文本的所有元素。

Firstly, does this seem like a feasible goal? jQuery makes it easy to use a selector to access a particular element, but I'm not sure if the reverse holds true. If an element lacks an id attribute, I also don't know how you'd return an "optimized" selector - i.e., one that identifies an element uniquely. Maybe crawl up the DOM until you find an ID, then stem the selector from there?

首先,这似乎是一个可行的目标吗? jQuery使得使用选择器访问特定元素变得容易,但我不确定反向是否成立。如果元素缺少id属性,我也不知道你如何返回“优化”选择器 - 即唯一标识元素的选择器。也许爬上DOM直到你找到一个ID,然后从那里阻止选择器?

Secondly, from a high-level perspective, any ideas on how to go about this? Any tips or tricks that could speed development? I very much appreciate any help.

其次,从高层次的角度来看,关于如何解决这个问题的任何想法?任何可以加速发展的提示或技巧?我非常感谢任何帮助。

Thanks!

谢谢!

1 个解决方案

#1


0  

I think you're looking for window.getSelection and window.getComputedStyle.

我想你正在寻找window.getSelection和window.getComputedStyle。

#1


0  

I think you're looking for window.getSelection and window.getComputedStyle.

我想你正在寻找window.getSelection和window.getComputedStyle。