我正在尝试创建一系列可编辑的段落,这些段落在单击按钮后获得焦点并变得可编辑;之后,我正在寻找一种方法,当段落失去焦点时,只需将其 contenteditable
属性设置为 false
;我根本不知道,也没有找到一种明确的方法来定位在处理元素数组时触发该函数的特定段落。
我确信可能存在语法错误或我根本没有遵循的规则,我仍在练习 JavaScript,所以我不知道该语言的所有工作原理。任何帮助表示赞赏
注意:如果有一种方法可以避免使用 onclick
HTML 属性并仅从 JavaScript 调用 editInfo
函数,那么也可以太棒了
这是我现在的代码
function editInfo(paragraph) {
var editableparagraph = document.getElementById(paragraph)
editableparagraph.setAttribute('contenteditable', 'true')
editableparagraph.focus();
}
var editableParagraph = document.getElementsByClassName('editable');
editableParagraph.onfocusout = function() {
editableParagraph.setAttribute('contenteditable', 'false');
}
<h4>About Me <button class="edit-btn" onclick="editInfo('about-me-p')">Edit</button></h4>
<p contenteditable="false" id="about-me-p" class="editable">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<h4>About You<button class="edit-btn" onclick="editInfo('about-you-p')">Edit</button></h4>
<p contenteditable="false" id="about-you-p" class="editable">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
最佳答案
根据您迄今为止分享的内容,听起来好像您已经拥有数组内页面的所有可编辑区域。根据您的评论,这似乎是一个引用实际元素
的数组,而不仅仅是其 ID 的数组。所以这是我的建议,不使用按钮:
// Note you may not need to pass in the array like I did.
function addListeners( array ){
// ADD CODE HERE FOR A FOR LOOP
// LOOP THROUGH THE ARRAY OF ELEMENTS
for(...){
// For all major browsers, except IE 8 and earlier
if ( array[x].addEventListener) {
array[x].addEventListener("click", makeEditable);
array[x].addEventListener("blur", removeEditable);
// For IE 8 and earlier versions
} else if (array[x].attachEvent) {
array[x].attachEvent("onclick", makeEditable);
array[x].attachEvent("onblur", removeEditable);
}
// END FOR LOOP
}
}
// Call our function to add the listeners. Make sure the page is loaded first!
addListeners( arrayOfElements);
function makeEditable(){
// ... Your code to make an area editable
}
function removeEditable(){
// ... Your code to remove content editable
}
如果您拥有的数组只是元素的 ID,您可以创建一个 for 循环来遍历数组并对数组中的每个项目执行 document.getElementById( ... )
,然后将元素引用而不是 ID 保存在数组中。
如果您想要/需要保留按钮,您可以做一些非常类似的事情。您可以使用与我创建的相同或类似的 addListeners
函数来将监听器添加到按钮,从而在正确的区域上运行 makeEditable
函数。然后,您需要在使该区域可编辑的同时添加一个 onblur
事件监听器,以便它知道在用户离开它时自行关闭。
希望这能让您朝着正确的方向前进。
关于javascript - 如何从数组中定位当前焦点元素来调用 focusout 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53822000/