我使用插件为可编辑的 div 手工制作了一个占位符。
如下面的演示所示。如果用户输入一些文本然后单击发布按钮,占位符就会消失。我想知道如何在发布后恢复占位符。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div id="topic_content_input" contenteditable="true" autocomplete="off" spellcheck="false" data-placeholder="placeholder text" ></div>
<button id="post">Post topic</button>
<style>
#topic_content_input[data-placeholder]:not([data-div-placeholder-content]):before {
content: attr(data-placeholder);
float: left;
cursor:text;
margin-left: 2px;
color: rgba(134,134,134,0.6);
}
#topic_content_input{
width:521px;
padding: 10px;
border: 1px solid orange;
}
#topic_content_input:focus{
outline-style:solid;
outline-color:orange;
outline-width:0px;
line-height:normal;
}
</style>
<script>
(function ($) {
$(document).on('change keydown keypress input', '#topic_content_input[data-placeholder]', function() {
if (this.textContent) {
this.dataset.divPlaceholderContent = 'true';
}
else {
delete(this.dataset.divPlaceholderContent);
}
});
})(jQuery);
</script>
<script>
$("#post").click(function(){
$("#topic_content_input").text("");
var obj=$("#topic_content_input");
// $("#topic_content_input").add(obj.dataset.divPlaceholderContent); //my attempt, not working
})
</script>
最佳答案
在 CSS 中,您可以输入 #topic_content_input,而不是使用
,只要 div 为空,就会放入占位符,如 jsfiddle 所示。 。 #topic_content_input[data-placeholder]:not([data-div-placeholder-content]):before
:empty:before
关于Javascript:如何修改我的代码以在主题发布后添加回消失的占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35282696/