Jquery:有没有办法在单击 Div 时突出显示它的文本?
使用 Jquery 有没有一种方法可以突出显示/选择(就像有人用鼠标选择它一样)我点击的 div 内的文本?不是一个文本框,只是一个普通的div。
我正在尝试制作一个“短网址”框,当有人单击文本区域时,它会突出显示所有文本,但它也不需要允许人们更改文本框中的文本,但是当文本框被禁用时,您无法选择任何文本,所以我正在尝试这样做,我只是认为 div 是最简单的。
抱歉,我一开始没有很好地解释我的意思,在上面添加了信息来澄清。
With Jquery is there a way to highlight/select(like if someone were to select it with the mouse) the text inside of a div that i click on? not a textbox, just a normal div.
i'm trying to make a 'short url' box, where when someone clicks on the textarea, it highlights all the text, but it also needs to NOT allow people to change the text in the textbox, but when a textbox is disabled you can't select any text, so i'm trying to do that, i just thought a div would be easiest.
sorry guys i didn't do a great job of explaining what i meant at first, added info above to clarify.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
是的,这与背景颜色无关,而是与选择文本有关。
首先将输入设置为只读,阻止人们更改值:
然后使用 jQuery(或类似的)在单击文本后选择文本:
您应该根据需要设置此输入的样式,也许可以使其看起来像普通的文本,看看这个 jsFiddle 以获得进一步的演示。
Right, this isn't about background colours, it's about selecting the text.
First set an input to readonly, stopping people changing the value:
Then using jQuery (or similar) to select the text once it's been clicked:
You should style this input as you see fit, perhaps to make it look like a normal bit of text, take a look at this jsFiddle for a further demonstration.
或者你可以添加一个类:
Or you can add a class:
单击元素后,您可以修改该元素的 CSS。像(未经测试)的东西:
You can modify the CSS of the element after it has been clicked. Something like (untested):
您可以使用文本区域,而不是禁用它,而是使用“只读”属性
You can use a textarea and instead of disabling it, use the 'readonly' attribute
这是我前段时间整理的一个快速而肮脏的无 jQuery 代码片段:
它可以进行很多改进(我特别讨厌过多的 try...catch 块),但它是一个很好的起点。 “节点”是指 DOM 树中的一个项目。
Here's a quick and dirty jQuery-less code snippet I put together some time ago:
It could use a lot of improvement (I specially hate the over-abundance of try...catch blocks) but it's a good starting point. With "node" I mean an item from the DOM tree.
工作演示
如果您只谈论单击而不是在任何内容中进行选择分区它会是这样的:
Working demo
If you talk only about clicking and not selecting inside any div. It would be something like this:
为什么不直接使用CSS:
why not just use css:
选择是由 DOM 中的范围对象定义的 - 因此您必须使用它们(document.createRange 或 document.createTextRange)。请参阅此线程: Selecting text in一个元素(类似于用鼠标突出显示)
A selection is defined by an range object in DOM - so you have to work with them (document.createRange or document.createTextRange). See this SO thread: Selecting text in an element (akin to highlighting with your mouse)