标记/选中/突出显示大写或小写的文本jQuery

时间:2017-08-04 11:11:26

标签: jquery text uppercase lowercase

有人可以帮助我,如何通过jQuery将btn点击中的标记文本转换为可疑div中的低位或大写?感谢您的回复。

<button type="button" id="asd" class="btn btn-info" onclick="replaceSelectedText(window.getSelection().toString().toUpperCase())">toUpper</button>

<script>
function replaceSelectedText(replacementText) {
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode(document.createTextNode(replacementText));
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.text = replacementText;
    }
}
</script>

2 个答案:

答案 0 :(得分:1)

You can try this:

function replaceSelectedText(_this) {
    
    var sel, range;
     var selectedText=window.getSelection().toString();
    if ($.trim(selectedText)!="") {
        sel = window.getSelection();
        
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            if($(_this).html().toString().toUpperCase()=="TOUPPER"){
            range.insertNode(document.createTextNode(selectedText.toString().toUpperCase()));
            $(_this).html("toLower");
            }
            else{
            range.insertNode(document.createTextNode(selectedText.toString().toLowerCase()));
            $(_this).html("toUpper");
            }
        }
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>


<button type="button" id="asd" class="btn btn-info" onclick="replaceSelectedText(this)">toUpper</button>

答案 1 :(得分:0)

You can make selected text to uppercase in content editable div. Check this jsfiddle

[0] http://jsfiddle.net/jignesh221290/7kmb2fm2/

For html tag you have to manage.