0
我在我的頁面bootstrap Dropdown component
:獲得所選元素
<div class="btn-group">
<button class="btn dropdown-toggle" data-toggle="dropdown" title="Police"><i class="fa fa-font"></i> <b class="caret"></b></button>
<ul class="dropdown-menu" id="fonts"></ul>
</div>
而且我使用這個腳本填補這一Dropdown component
:
var fonts = [
'Serif',
'Sans',
'Arial',
'Arial Black',
'Courier',
'Courier New',
'Comic Sans MS',
'Helvetica',
'Impact',
'Lucida Grande',
'Lucida Sans',
'Tahoma',
'Times',
'Times New Roman',
'Verdana'
];
var fontsDropDown = document.getElementById('fonts');
fonts.forEach(function(police){
var li = document.createElement('li');
var a = document.createElement('a');
a.style = "font-family:'" + police + "'";
a.appendChild(document.createTextNode(police));
li.appendChild(a);
fontsDropDown.appendChild(li);
});
而且我有一個可編輯div
:
<div id="editor" contentEditable="true"> Enter your text here.. </div>
我想要當我選擇一些元素在Dropdown component
變更爲可編輯的div所選文本的字體,我試圖在<ul>
添加事件監聽每個<a>
爲Dropdown component
:
var fontsArray = Array.prototype.slice.call(document.querySelectorAll('#fonts li a'));
fontsArray.forEach(function(value){
value.addEventListener('click', function(){
document.execCommand('fontName', false, value);
}, false);
});
,但它不工作,我想上的按鈕測試document.execCommand('fontName', false, value);
爲Dropdown component
直接爲以下幾點:
document.getElementById('fonts').addEventListener('click', function(){
document.execCommand('fontName', false, 'Comic Sans MS');
}, false);
和它的作品,所以我想我只需要得到對Dropdown component
「選定的元素值,併爲document.execCommand()
第三個參數替換它。
我累了,以搜索做腳本,和所有我能找到的是使用jQuery:
$(function(){
$(".dropdown-menu li a").click(function(){
$(".btn:first-child").text($(this).text());
$(".btn:first-child").val($(this).text());
});
});
但我想用純JavaScript來獲得所選擇的項目。
我該怎麼做?