Das*_*sun 8 html javascript jquery
我正在使用 html 内置contenteditable功能实现自定义文本编辑器。我需要知道用户何时在文本编辑器上选择了文本是否为粗体。
这是我现在所拥有的:
HTML
<button onclick="boldit()">B</button>
<div id="editor" contenteditable="true" class="email-body">
This is an <strong>editable</strong> paragraph.
</div>
Run Code Online (Sandbox Code Playgroud)
Javascript
function boldit(){
document.execCommand('bold');
}
Run Code Online (Sandbox Code Playgroud)
Bri*_*and 10
可靠的方法是遍历父树检查getComputedStyle。
我假设您已经拥有选定的元素。
function isBold(_element) {
var element = _element;
while (element) {
var style = getComputedStyle(element).fontWeight;
if (Number(fontWeight) > 400 || fontWeight === 'bold' || fontWeight === 'bolder') {
return true;
}
element = element.parentNode;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
jQuery(function($) {
$('.embolden').click(function(){
if(selectionIsBold()){
alert('bold');
}
else {
alert('not bold');
}
});
});
function selectionIsBold() {
var isBold = false;
if (document.queryCommandState) {
isBold = document.queryCommandState("bold");
}
return isBold;
}Run Code Online (Sandbox Code Playgroud)
.bold {
font-weight: bold;
}Run Code Online (Sandbox Code Playgroud)
<div contenteditable="true" class="textEditor">Some <span class="bold">random </span>text.</div>
<a href="#" class="embolden">Is Bold Text</a>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>Run Code Online (Sandbox Code Playgroud)
突出显示文本并单击链接。
| 归档时间: |
|
| 查看次数: |
3873 次 |
| 最近记录: |