gpt4 book ai didi

javascript - 如何在单击元素时设置 contenteditable true

转载 作者:太空宇宙 更新时间:2023-11-04 01:46:00 25 4
gpt4 key购买 nike

我有一个数组。我在其中存储了标签列表。现在我想要的是,单击 ( h1, a, strong ) 之类的元素时,它将在给定数组中找到标签并在元素上应用 contenteditable true。在标签或其他元素外部单击时,contenteditable 将再次设置为 false。

目前我正在使用此代码来更改 contenteditable true,但如果我想编辑 p,我必须为 p 编写一个新代码,与 strong h2、h3、h4 等相同

$('h1').click(function(event) {
$(this).attr('contenteditable', 'true');
});

$(function(){

$(".textTemplate").draggable({
helper: "clone",
zIndex: 2500
});

$( ".editorDesignView" ).droppable({
accept: '.textTemplate',
drop: function( event, ui ) {
var html = `<div id="" class="dynamic"><h1 contenteditable="false">Title</h1><p contenteditable="false" style="padding: 5px;">Add your text here.</p></div>`;
$(html).appendTo(this).hide().slideDown();
}
});

$(document).on('click', 'h1', function(event) {
event.preventDefault();
$(this).attr('contenteditable', 'true');
});
});
* {box-sizing: border-box;}
#wrapper {width: 100%; height: 100vh;}
.templateWrapper {width: 30%; height: 100%;float:left;overflow-y: scroll;}
.editorBlock {width: 70%; height: 100%;float:left;position: relative;background-color:#f1f1f1}


.editorDesignView {width: 100%; height: 100%;}

.dynamic {
background: #4073ff;width: 80%; margin: 10px auto; padding: 10px;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

<div id="wrapper">
<div class="templateWrapper">
<div class="textTemplate" style="margin-top:20px;" class="template">
<div>drag me</div>
</div>


</div>
<div class="editorBlock" style="height:100%;">
<div class="editorDesignView" style="height:100%;"></div>
</div>
</div>

最佳答案

你可以用下面的代码来做到这一点。

将事件附加到除 html、body 和 div 之外的所有元素以使内容可编辑,并为其他元素附加事件以使非内容可编辑。

根据您的要求,您可以在逗号分隔的 $array 中添加选择器。

var $array=[ 'body', 'div', 'html' ];
var notSelectorString = $array.join(",");
$('*').not(notSelectorString).on('click', function(event) {
$(this).attr('contenteditable', 'true');
}).on("focusout",function(e){ $(this).attr('contenteditable', 'false');});

$(notSelectorString).on('click', function(event) {
$(this).attr('contenteditable', 'false');
});

关于javascript - 如何在单击元素时设置 contenteditable true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44544812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com