appliquer le style avec execCommand le texte arbitraire
-
27-10-2019 - |
Question
Je sais comment exécuter execCommand
sur un texte sélectionné, mais est-il un moyen d'exécuter sur un autre texte dans mon contenteditable
div?
La solution
In IE, yes. In other browsers, no.
All major desktop browsers implement some form of document.execCommand()
, which acts only on the user selection. In IE, the TextRange
object also has an execCommand
method. For example, the following will turn the text contents of an element green when the user hovers the cursor over it:
<div id="test">Here is a test div</div>
<script type="text/javascript">
var div = document.getElementById("test");
div.onmouseover = function() {
if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(div);
textRange.execCommand("foreColor", false, "green");
}
};
</script>
Autres conseils
In case you are not aware, the .execCommand
is an IE only non-standard javascript function that should be avoided.
If you tell us what you want to use it for, then we could suggest a standards-compliant alternative.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow