简体   繁体   English

使用Java脚本更改所选文本的行高

[英]Change the line height of the selected text with Javascript

I am trying to program my own WYSIWYG editor as a summer project. 我试图将自己的所见即所得编辑器编程为一个夏季项目。 I am trying to implement the line height function that controls(single spacing, double spacing, etc). 我正在尝试实现控制(单间距,双倍间距等)的线高功能。 I have created the dropdown that will allow users to select between the types of spacing. 我创建了一个下拉菜单,允许用户在间距类型之间进行选择。 However, I cannot seem to get the right Javascript, because the selected text does not change in line spacing at all no matter which option I choose. 但是,我似乎无法获得正确的Javascript,因为无论选择哪种选项,所选文本根本不会改变行距。 Can someone please take a look at my Javascript and tell me where I went wrong? 有人可以看看我的Javascript并告诉我我哪里出了问题吗? If possible, can you give me the correct code for the Javascript so I can refer off of it? 如果可能的话,您能给我正确的Java代码以便我参考吗? Thank you! 谢谢!

HTML(working): HTML(有效):

 <select id="lineHeight" onchange="spacing(this)">
                                <option value="20px">20px</option>
                                <option value="80px">80px</option>
                                <option value="100px">100px</option>
                                <option value="200px">200px</option>
                            </select>

Javascript(not working) Javascript(不起作用)

function spacing(sel) {
        var text = editor.document.getSelection();
        text.style.lineHeight = sel.value;
    }

If I understand what you're trying to do, perhaps this will work for you: 如果我了解您要做什么,那么这可能对您有用:

 function changeStyle( property, value ) { if ( window.getSelection().rangeCount ) { var range = window.getSelection().getRangeAt( 0 ), contents = range.extractContents(), span = document.createElement( 'span' ); span.style[ property ] = value; span.appendChild( contents ); range.insertNode( span ); window.getSelection().removeAllRanges() } } 
 #editor { width: 350px; max-height: 100px; padding: 20px; overflow-y: auto; background-color: #efefef; border: 1px solid #ddd } 
 <p> <label for="lineHeight">Line Height: </label> <select id="lineHeight" onchange="changeStyle('line-height', this.value)"> <option value="20px">20px</option> <option value="80px">80px</option> <option value="100px">100px</option> <option value="200px">200px</option> </select> <button onclick="changeStyle('font-weight', 'bold')">Bold</button> <button onclick="changeStyle('font-style', 'italic')">Italic</button> <button onclick="changeStyle('color', 'red')">Color</button> <button onclick="changeStyle('background-color', 'yellow')">Background</button> </p> <div id="editor" contenteditable>Change the line height of the selected text with Javascript:<br>Please note that this example should be completed.</div> 

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

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