document.execCommand() FontSize in pixels?

后端 未结 8 1980
一向
一向 2020-11-29 06:55

How can I change font size to 30px (for example) using document.execCommand?

This:

document.execCommand(\"fontSize\", false, \"30px\");
         


        
8条回答
  •  甜味超标
    2020-11-29 07:24

    $(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, 'X');
    			//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}
    
    
    Hello, this is some editable text

提交回复
热议问题