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.
Right, this isn't about background colours, it's about selecting the text.
First set an input to readonly, stopping people changing the value:
<input type="text" readonly="readonly" value="ABC" />
Then using jQuery (or similar) to select the text once it's been clicked:
$('input').click(function() {
$(this).select();
});
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.
$("div.myDiv").click(function() {
$(this).css("background-color", "yellow");
})
Or you can add a class:
$("div.myDiv").click(function() {
if($(this).hasClass("highlited")) {
$(this).removeClass("highlited");
} else {
$(this).addClass("highlited");
}
}
You can modify the CSS of the element after it has been clicked. Something like (untested):
$(".el").click( function() {
$(".el").css( "color", "red" ).css( "background-color", "yellow" );
});
You can use a textarea and instead of disabling it, use the 'readonly' attribute
<textarea name="selectable" readonly="readonly" />
Here's a quick and dirty jQuery-less code snippet I put together some time ago:
/*
* Creates a selection around the node
*/
function selectNode(myNode){
// Create a range
try{ // FF
var myRange = document.createRange();
}catch(e){
try{ // IE
var myRange = document.body.createTextRange();
}catch(e){
return;
}
}
// Asign text to range
try{ // FF
myRange.selectNode(myNode);
}catch(e){
try{ // IE
myRange.moveToElementText(myNode);
}catch(e){
return;
}
}
// Select the range
try{ // FF
var mySelection = window.getSelection();
mySelection.removeAllRanges(); // Undo current selection
mySelection.addRange(myRange);
}catch(e){
try{ // IE
myRange.select();
}catch(e){
return;
}
}
}
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:
$("div").click(function()
{
$(this).css({"background":"yellow"});
});
why not just use css:
div.<someclass>:focus {
background:yellow;
}
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)
精彩评论