Possible Duplicate:
How to use the Javascript to add/remove the CSS/colour style to the html page?
I have a question on the HTML and javascript. I got the following paragrahe.
function add_span(){
// ??
}
<input type="button" onclick="add_span()" value="add span"/>
<p> statement1, statement2, statement3 </p>
Is it possible to have the following result after the user
- select the highlighte开发者_Go百科d text by mouse
- click the button
e.g.
- highlight the 'statement1,'
- click the button
Expected Result:
<input tupe="button" onclick="add_span()" value"add span"/>
<p> <span class="ABC">statement1,</span> statement2, statement3 </p>
##### Updated Code, but no work
// updated code in the add_span
var selectedText;
if (window.getSelection)
{
selectedText = window.getSelection();
}
else if (document.getSelection) // FireFox
{
selectedText = document.getSelection();
}
else if (document.selection) // IE 6/7
{
selectedText = document.selection.createRange().text;
}
//create the DOM object
var newSpan = document.createElement('span');
// add the class to the 'spam'
newSpan.setAttribute('class', 'ABC');
document.getElementById('text').appendChild(newSpan);
var selectedTextNode = document.createTextNode();
newSpan.appendChild(selectedTextNode);
You can get selected text from @Pezhvak IMV's answer:
var selectedText;
if (window.getSelection)
{
selectedText = window.getSelection();
}
else if (document.getSelection) // FireFox
{
selectedText = document.getSelection();
}
else if (document.selection) // IE 6/7
{
selectedText = document.selection.createRange().text;
}
To add a element, you have to create a DOM node, set its attributes and add the element:
Create a DOM node:
var newSpan = document.createElement('span');
Set the class
newSpan.setAttribute('class', 'ABC');
Add the span to under the
<p>
(The<p>
should have a id or some mechanism of identifying it:<p id="text">
Add the
<span>
to under the<p>
document.getElementById('text').appendChild(newSpan);
And set the text
newSpan.innerHTML = selectedText;
You can also use createTextNode
(alternative for step 5)
var selectedTextNode = document.createTextNode();
newSpan.appendChild(selectedTextNode);
To answer part of you question:
function getSelText() {
var txt = '';
if (window.getSelection)
{
txt = window.getSelection();
}
else if (document.getSelection) // FireFox
{
txt = document.getSelection();
}
else if (document.selection) // IE 6/7
{
txt = document.selection.createRange().text;
}
else return; document.aform.selectedtext.value = txt; }
精彩评论