document.execcommand()fontsize in pixels?
-
28-10-2019 - |
質問
フォントサイズを30pxに変更するにはどうすればよいですか(たとえば) document.execCommand
?
これ:
document.execCommand("fontSize", false, "30px");
機能ExecCommandの3番目の引数では、1〜7を含む値を入力することのみを可能にするため、機能しません。
解決
それはの制限です FontSize
指図。私が考えることができるさまざまなオプションがあります:
- 代わりにCSSクラスを使用して、 CSSクラスアプリダー 私のモジュール ランジー 図書館;
- 呼び出しなど、ハッキーな方法を使用できます
document.execCommand("fontSize", false, "7");
そして、コマンドが作成した要素を見つけて、必要に応じてそれらを変更します。例を参照してください: http://jsfiddle.net/s3ctn/. 。これは明らかに他にないことに依存します<font>
ドキュメントにサイズ7の要素があり、それはブラウザを使用してブラウザにも依存しています<font>
フォントサイズの要素。
他のヒント
関数
var execFontSize = function (size, unit) {
var spanString = $('<span/>', {
'text': document.getSelection()
}).css('font-size', size + unit).prop('outerHTML');
document.execCommand('insertHTML', false, spanString);
};
実行する
execFontSize(30, 'px');
2番目の答えが示唆するように、execcommandの後にJqueryを実行し、マークアップを独自のものに置き換えます。
Elemを要素に置き換えて、Font-Sizeを目的の値で編集してください。
jQuery("font[size]", elem).removeAttr("size").css("font-size", "10px");
CSSでオーバーライドするだけです:
font[size='7']{
font-size: 20px; // or other length unit
}
または、SCSSを使用する場合は、ループを使用して1〜7のすべてのセレクターを生成できます。
@for $i from 1 to 7 {
font[size='#{$i}']{
font-size: $i * 2vw
}
}
$(document).ready(()=>{
var activeFontSize = 30;
var oDoc = document.getElementById("editor");
var style = document.createElement("style");
document.body.appendChild(style);
function setFontSize(value){
$editor.focus();
document.execCommand("fontsize", false, 20);
activeFontSize = value;
createStyle();
updateTags();
}
function updateTags(){
var fontElements = oDoc.getElementsByTagName("font");
for (var i = 0, len = fontElements.length; i < len; ++i) {
if (fontElements[i].size == "7") {
fontElements[i].removeAttribute("size");
fontElements[i].style.fontSize = activeFontSize+"px";
}
}
}
function createStyle(){
style.innerHTML = '#editor font[size="7"]{font-size: '+activeFontSize+'px}';
}
function updateToolBar(args){
$fontSize.val(args.fontsize);
}
var $fontSize = $("#fontSize");
var $editor = $("#editor");
$fontSize.on("change", ()=>{
setFontSize($fontSize.val())
})
$editor.on("keyup", ()=>{
updateTags();
})
//var i = 0;
$editor.on("keyup mousedown", (e)=>{
//i++;
//console.log("e.target", e.target)
try{
var fontsize = $(window.getSelection().getRangeAt(0).startContainer.parentNode).css("font-size")
fontsize = fontsize.replace("px", "");
//document.execCommand("insertHTML", false, '<span class="font-size-detector'+i+'">X</span>');
//var fontsize = $(e.target).css("font-size")//$editor.find(".font-size-detector"+i).css("font-size");
//document.execCommand("undo", false, false);
//$editor.focus();
//console.log("fontsize", fontsize)
updateToolBar({fontsize})
}catch(e){
console.log("exception", e)
}
})
oDoc.focus();
setFontSize(30);
})
.editor-box{box-shadow:0px 0px 1px 2px #DDD;max-width:500px;margin:0px auto;}
.editor-tools{padding:20px;box-shadow:0px 2px 1px 0px #DDD}
.editor-tools button{user-select:none;}
#editor{height:200px;margin:10px 0px;padding:10px;font-size:14px;}
#editor:focus{outline:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="editor-box">
<div class="editor-tools">
<label>Font Size: </label>
<select id="fontSize" >
<option value="10">10px</option>
<option value="12">12px</option>
<option value="14">14px</option>
<option value="20">20px</option>
<option value="22">22px</option>
<option value="30" selected="true">30px</option>
<option value="35">35px</option>
<option value="40">40px</option>
<option value="45">45px</option>
<option value="50">50px</option>
</select>
</div>
<div id="editor" contenteditable="true">Hello, this is some editable text</div>
</div>
それは私のソリューションだけです。それはChromeで動作します。このコードは、中国のウェブサイト(EQXIU)で見つかりました。
最初
document.execCommand("styleWithCSS", 0, true);
document.execCommand('fontSize', 0, '12px');
それから
jQuery.find('[style*="font-size: -webkit-xxx-large"],font[size]').css("font-size", "12px")
注:execCommandへのfontsizeパスは、少なくとも「12px」以上でなければなりません。
選択したテキストからフォントサイズを変更する要素を直接取得するため、ここで提案されている多くの人よりも優れたソリューションがあります。
結果として、適切な要素を取得するためにDOMを閲覧する必要はなく、特定のfontsizeの使用を禁止する必要はありません(7、受け入れられた回答の最初のオプションで示唆されているように、および他の回答で)。
function changeFont() {
document.execCommand("fontSize", false, "7");
var fontElements = window.getSelection().anchorNode.parentNode
fontElements.removeAttribute("size");
fontElements.style.fontSize = "30px";
}
要約すると、execCommandを使用して選択をスパンで包むだけで、その後のgetSelection()whillへの呼び出しは、強調表示されたスパンを親として持つようにします。次に、その識別されたスパンにfontsizeスタイルを追加するだけです。
ここで、fontsizeコマンドを使用しているので、 <span>
, 、しかし、 <font>
.
しかし、これはexecCommandの任意のコマンドで動作する一般的な方法であり、後者は、選択したコンテンツを異なる要素間でも包むのに便利な方法として使用されます。
これがライブです デモ
カスタムHTML(色、フォントファミリ)を備えた複数の行で機能する純粋なJavaScriptのソリューションを見つけました。
ドキュメントの選択を取得します。選択を解析し、HTMLタグをそこから保存します。次に、document.execcommandで、選択したHTMLをインラインスタイルのDIV内に挿入します。また、document.execcommand( 'inserthtml'、false、html)を使用する場合の利点は、wysiwygエディターで元に戻すことです。
これが関数です:
function fontSize(size) {
var sel = document.getSelection(); // Gets selection
var selectedHtml = "";
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
selectedHtml = container.innerHTML;
}
let html = `<div style="font-size: ${size}px;">${selectedHtml}</div>`
document.execCommand('insertHTML', false, html);
}
それが役に立てば幸い。