大写文本区域中的文本选择

Upper case a selection of text in a textarea

我尝试 运行 以下代码时遇到 undefined is not a function 错误:

$(document).ready(function() {
    $("#textarea").select(function() {
        var selection = window.getSelection();
        $("#upper").click(function() {
            // alert(selection);
            var upper = selection.toUpperCase();
            var text = $("#textarea").text();
            $("#textarea").html(text.replace(selection, upper));
        });
    }); 
});

我正在尝试 select 来自文本区域的文本,然后单击一个按钮使 selection 变为大写。这是完整代码的JSFiddle

getSelection returns 一个对象。您需要对其调用 toString()

$(document).ready(function () {
    var selection;
    $("#textarea").select(function () {
        selection = window.getSelection().toString();
    });
    $("#upper").click(function () {
        if (selection) {
            var upper = selection.toUpperCase();
            var text = $("#textarea").text();
            $("#textarea").html(text.replace(selection, upper));
        }
    });
});

JSFiddle:http://jsfiddle.net/TrueBlueAussie/8syb2d8j/4/

备注:

  • 您的事件处理程序是嵌套的(通常是个坏主意)
  • 我添加了一个检查以确保在尝试大写之前有一个选择。
  • 因为,您突出显示的文本可能会出现多个,因此使用 replace 实际上并不是一个很好的解决方案。尝试突出显示第二个 i 看看我的意思。您应该使用选择对象的属性来计算出所选字符串的确切部分,

浏览便携式解决方案后,我发现 jQuery TextRange plugin, which, based on the demo 足以解决此问题。