将所选文本设为粗体/非粗体

时间:2014-01-02 09:55:08

标签: javascript jquery

当您单击按钮时,我将所选文本包装在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 Demo

我可能对此请求感到贪婪,但我只选择已包含在span标签中的文本的一部分,但不是全部,我想在选择开始时关闭原始标签,在此之后打开一个新标签,然后在选择结束时关闭新标签并在此之后打开一个新标签。

8 个答案:

答案 0 :(得分:38)

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

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

并且所选文本将变为粗体,如果它已经是粗体,则将删除文本样式。

可以找到命令列表和一些小文档here。 (有关浏览器支持的更多信息here)。

$(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>

答案 1 :(得分:2)

此答案的复制功能:Get parent element of a selected text

还没有真正完善这一点,我认为这只适用于精确的选择,但它让你知道如何解决这个问题。 click函数检查当前选择的父元素是否具有“粗体”类,如果是,则再次用原始选择替换该元素。

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;
}

答案 2 :(得分:1)

终于明白了:

<!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-属性。它们应该是不言自明的。

这也将取消应用于当前目标元素内的所选文本的子部分(所有内容都按类名称)。

正如你所看到的,我正在使用一个由一组东西组成的类,所以这会给你更多的功能。

答案 3 :(得分:0)

此代码通过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));
    });
});

答案 4 :(得分:0)

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

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));
    });
});

答案 5 :(得分:0)

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

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

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

答案 6 :(得分:0)

如果您希望使用键盘来加粗字符,则可以使用以下( 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')
    }
  }
}) 

使用键盘加粗字符:

enter image description here

答案 7 :(得分:-1)

check this 这是你想要的吗?

使用

.toggleclass()

(仅使文本编辑器类中的所有文本都为粗体)

相关问题