繁体   English   中英

将所选文字设为粗体/粗体

[英]Make selected text bold/unbold

当您单击按钮时,我会将选定的文本包装在span标签中。 如果我随后选择另一段文本并单击按钮,则该文本也将包裹在标签中。 但是,当我选择一段已经用span标签包裹的文本时,我想删除这些标签以取消显示文本,而不是将这些标签包裹在更多标签中。

的HTML

<div contenteditable="true" class="textEditor">Some random text.</div>

<a href="#" class="embolden">Bold</a>

JS

$('.embolden').click(function(){
    var highlight = window.getSelection();  
    var span = '<span class="bold">' + highlight + '</span>';
    var text = $('.textEditor').html();
    $('.textEditor').html(text.replace(highlight, span));
});

JSFiddle演示

我可能对此要求很满意,但我只选择了已经用span标记包裹的一段文本,但不是全部,我想在选择开始时关闭原始标记,打开一个之后立即添加新标签,然后在选择的最后关闭新标签,然后再打开一个新标签。

当您可以使用内置功能时,为什么要尝试用粗体显示文本。 现代浏览器实现了execCommand函数,该函数允许在文本上加粗,加下划线等。 您可以只写:

$('.embolden').click(function(){
    document.execCommand('bold');
});

并将选定的文本设置为粗体,如果已经将其设置为粗体,则将删除文本样式。

命令列表和一些文档可以在这里找到。 (有关浏览器支持的更多信息,请点击此处 )。

 $(document).ready(function() { $('#jBold').click(function() { document.execCommand('bold'); }); }); 
 #fake_textarea { width: 100%; height: 200px; border: 1px solid red; } button { font-weigth: bold; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="jBold"><b>B</b></button> <div id='fake_textarea' contenteditable> Select some text and click the button to make it bold... <br>Or write your own text </div> 

从此答案复制的功能: 获取所选文本的父元素

还没有真正完善它,我认为这仅适用于确切的选择,但是它为您提供了解决方法。 click函数检查当前选择的父元素是否具有“ bold”类,如果是,它将再次用原始选择替换该元素。

http://jsfiddle.net/XCb95/4/

jQuery(function($) {
    $('.embolden').click(function(){
        var highlight = window.getSelection();  
        var span = '<span class="bold">' + highlight + '</span>';
        var text = $('.textEditor').html();

       var parent = getSelectionParentElement();
        if($(parent).hasClass('bold')) {
              $('.textEditor').html(text.replace(span, highlight));
        } else {
            $('.textEditor').html(text.replace(highlight, span));
        }

    });
});

function getSelectionParentElement() {
    var parentEl = null, sel;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            parentEl = sel.getRangeAt(0).commonAncestorContainer;
            if (parentEl.nodeType != 1) {
                parentEl = parentEl.parentNode;
            }
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        parentEl = sel.createRange().parentElement();
    }
    return parentEl;
}

终于明白了:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.emphasized {
  text-decoration: underline;
  font-weight: bold;
  font-style: italic;
}
</style>
</head>
<body>
  <button type="button" onclick="applyTagwClass(this);" data-tag="span" data-tagClass="emphasized">Bold</button>
  <div contenteditable="true" class="textEditor">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In malesuada quis lorem non consequat. Proin diam magna, molestie nec leo non, sodales eleifend nibh. Suspendisse a tellus facilisis, adipiscing dui vitae, rutrum mi. Curabitur aliquet
      lorem quis augue laoreet feugiat. Nulla at volutpat enim, et facilisis velit. Nulla feugiat quis augue nec sodales. Nulla nunc elit, viverra nec cursus non, gravida ac leo. Proin vehicula tincidunt euismod.</p>
    <p>Suspendisse non consectetur arcu, ut ultricies nulla. Sed vel sem quis lacus faucibus interdum in sed quam. Nulla ullamcorper bibendum ornare. Proin placerat volutpat dignissim. Ut sit amet tellus enim. Nulla ut convallis quam. Morbi et
      sollicitudin nibh. Maecenas justo lectus, porta non felis eu, condimentum dictum nisi. Nulla eu nisi neque. Phasellus id sem congue, consequat lorem nec, tincidunt libero.</p>
    <p>Integer eu elit eu massa placerat venenatis nec in elit. Ut ullamcorper nec mauris et volutpat. Phasellus ullamcorper tristique quam. In pellentesque nisl eget arcu fermentum ornare. Aenean nisl augue, mollis nec tristique a, dapibus quis urna.
      Vivamus volutpat ullamcorper lectus, et malesuada risus adipiscing nec. Ut nec ligula orci. Morbi sollicitudin nunc tempus, vestibulum arcu nec, feugiat velit. Aenean scelerisque, ligula sed molestie iaculis, massa risus ultrices nisl, et placerat
      augue libero vitae est. Pellentesque ornare adipiscing massa eleifend fermentum. In fringilla accumsan lectus sit amet aliquam.</p>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <script>
      function applyTagwClass(self) {
        var selection = window.getSelection();
        if (selection.rangeCount) {
          var text = selection.toString();
          var range = selection.getRangeAt(0);
          var parent = $(range.startContainer.parentNode);
          if (range.startOffset > 0 && parent.hasClass(self.attributes['data-tagClass'].value)) {
            var prefix = '<' + self.attributes['data-tag'].value + ' class="' + self.attributes['data-tagClass'].value + '">' + parent.html().substr(0,selection.anchorOffset) + '</' + self.attributes['data-tag'].value + '>';
            var suffix = '<' + self.attributes['data-tag'].value + ' class="' + self.attributes['data-tagClass'].value + '">' + parent.html().substr(selection.focusOffset) + '</' + self.attributes['data-tag'].value + '>';
            parent.replaceWith(prefix + text + suffix);
          } else {
            range.deleteContents();
            range.insertNode($('<' + self.attributes['data-tag'].value + ' class="' + self.attributes['data-tagClass'].value + '">' + text + '</' + self.attributes['data-tag'].value + '>')[0]);
            //Remove all empty elements (deleteContents leaves the HTML in place)
            $(self.attributes['data-tag'].value + '.' + self.attributes['data-tagClass'].value + ':empty').remove();
          }
        }
      }
    </script>
</body>
</html>

您会注意到,我将按钮扩展为具有几个data- attribute。 他们应该是不言自明的。

这还将取消应用于当前目标元素内的所选文本的各个小节(所有内容均按类名进行)。

如您所见,我正在使用一个类,这些类是事物的组合,因此可以为您提供更多的多功能性。

此代码通过textEditor的内容,并删除所有span标签。 它应该可以解决问题。

jQuery(function($) {
    $('.embolden').click(function(){
        $('.textEditor span').contents().unwrap();
        var highlight = window.getSelection();  
        var span = '<span class="bold">' + highlight + '</span>';
        var text = $('.textEditor').html();
        $('.textEditor').html(text.replace(highlight, span));
    });
});

这样的事情应该可以解决问题:

var span = '';

jQuery(function($) {
    $('.embolden').click(function(){
        var highlight = window.getSelection();
        if(highlight != ""){
            span = '<span class="bold">' + highlight + '</span>';
        }else{
            highlight = span;
            span = $('span.bold').html();
        }
        var text = $('.textEditor').html();
        $('.textEditor').html(text.replace(highlight, span));
    });
});

现代浏览器利用execCommand函数,使您可以非常轻松地加粗文本。 它还提供其他样式,例如下划线等。

<a href="#" onclick="emboldenFont()">Bold</a>

function emboldenFont() {
    document.execCommand('bold', false, null);
}

如果要使用键盘将字符加粗,可以使用以下命令( Mac ):

$(window).keydown(function(e) {
  if (e.keyCode >= 65 && e.keyCode <= 90) {
    var char = (e.metaKey ? '⌘-' : '') + String.fromCharCode(e.keyCode)
    if(char =='⌘-B') {
    document.execCommand('bold')
    }
  }
}) 

使用键盘将字符加粗:

在此处输入图片说明

检查这就是你想要的???

使用

.toggleclass()

(仅使文本编辑器类中的所有文本加粗)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM