如何以 div 作为背景来模仿 JS 范围/选择?
我需要模仿范围/选择(那些突出显示网站上的内容,当您按 CTRL + C
时,您会复制内容),并以 div 作为背景。 “突出显示 div”很可能是 position:absolute;
<div id="highlight">
<!-- The highlightor divs would go here -->
</div>
<div id="edit">
<!-- The divs to be highlighted (that have text) would go here -->
</div>
编辑:复制等功能至关重要。
PS:如果您对“为什么”感到好奇,请参阅 此问题。 我创建了一个新问题,因为我觉得旧问题已经得到了很好的回答,而且这个问题与那个问题有很大不同。
I need to mimic ranges/selections (those that highlight content on a website, and when you press for ex CTRL + C
you copy the content) with divs as backgrounds. Chances are that the "highlighting divs" will be position:absolute;
<div id="highlight">
<!-- The highlightor divs would go here -->
</div>
<div id="edit">
<!-- The divs to be highlighted (that have text) would go here -->
</div>
Edit: Functionalities such as copying are essential.
PS: If you're curious about "why", refer to this question.
I created a new question because I felt the old one was pretty much answered, and this one differed to much from that one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是概念,并有一些代码可以帮助您入门。每次在页面中选择文本时,将该文本附加到页面上的隐藏文本区域,然后选择该文本区域。然后,将原始选择包裹在一个跨度中,使其看起来像是被选中的。这样,您就有了选择的外观,并且由于实际上选择了隐藏的文本区域,因此当用户点击“ctrl+c”时,他们正在从文本区域复制文本。
为了获得您正在寻找的完整功能,您可能需要扩展它。嗅探“ctrl+a”键(用于全选)。我认为您无法覆盖右键单击行为……至少不能轻松或优雅地覆盖。但这至少是一个可供您运行的概念证明。
这是我在测试中用来隐藏文本区域并设置所选文本样式的 css:
Here's the concept, with some code to get you started. Every time text is selected in the page, append that text to a hidden textarea on the page and then select the textarea. Then, wrap the original selection in a span to make it look selected. This way, you have the appearance of a selection, and since the hidden textarea is actually selected, when the user hits "ctrl+c" they are copying the text from the textarea.
To get the full functionality you are looking for, you'll probably want to extend this. Sniff keys for "ctrl+a" (for select all). I don't think you'll be able to override right-click behavior... at least not easily or elegantly. But this much is at least a proof of concept for you to run with.
Here's the css I used in my test to hide the textarea and style the selected text: