簡體   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