Nice programing

contenteditable div의 자리 표시 자

nicepro 2020. 12. 30. 20:26
반응형

contenteditable div의 자리 표시 자


다음이 있습니다 : FIDDLE

당신이 뭔가를 입력 할 때까지 자리 벌금과 멋쟁이 작동 ctrl+ A,와 delete. 그렇게하면 자리 표시자가 사라지고 다시 나타나지 않습니다.

뭐가 문제 야? contenteditable div에 대한 자리 표시자를 어떻게 가질 수 있습니까?

HTML :

<div class="test" placeholder="Type something..." contenteditable="true"></div>


CSS :

.test {
    width: 500px;
    height: 70px;
    background: #f5f5f5;
    border: 1px solid #ddd;
    padding: 5px;
}

.test[placeholder]:empty:before {
    content: attr(placeholder);
    color: #555; 
}


감사.


동일한 문제를 검색하는 동안 공유하고 싶은 간단한 혼합 css-JavaScript 솔루션을 찾았습니다.

CSS :

[placeholder]:empty::before {
    content: attr(placeholder);
    color: #555; 
}

[placeholder]:empty:focus::before {
    content: "";
}

자바 스크립트 :

jQuery(function($){
    $("[contenteditable]").focusout(function(){
        var element = $(this);        
        if (!element.text().trim().length) {
            element.empty();
        }
    });
});

업데이트 된 바이올린


에서 포커스 이벤트 문제 -의 contentEditable에 자리 표시 자

[contentEditable=true]:empty:not(:focus):before{
  content:attr(data-ph);
  color:grey;
  font-style:italic;
}

일부 수정 :

1) $element.text().trim().length- 이는 문제를 해결 <div><br/></div>하고&nbsp;

2) data-placeholderattr 대신 placeholder-진정한 방법입니다.

3) 공통 선택기 $("[contenteditable]")-진정한 방법입니다.

4) display: inline-block;-Chrome 및 Firefox 수정

자바 스크립트 :

jQuery(function($){
    $("[contenteditable]").blur(function(){
        var $element = $(this);
        if ($element.html().length && !$element.text().trim().length) {
            $element.empty();
        }
    });
});

HTML :

<div data-placeholder="Type something..." contenteditable="true"></div>

CSS :

[contenteditable]:empty:before {
    content: attr(data-placeholder);
    color: grey;
    display: inline-block;
}

무슨 말인지 알겠습니다. 바이올린에서 몇 글자를 입력하고 'ctrl-a'와 '삭제'를 사용하여 삭제했고 자리 표시자가 다시 나타납니다.

그러나 contenteditabele div 내에서 'enter'를 누르면 자식 <div><br></div>요소가없는 요소 만 대상으로하는 : empty 의사 클래스 문제를 만드는 줄 바꿈이 포함 된 자식 div가 생성되는 것처럼 보입니다 . **

Chrome 개발자 도구 또는 사용하는 모든 항목에서 확인하십시오.

developer.mozilla.org에서

: empty 가상 클래스는 자식이 전혀없는 모든 요소를 ​​나타냅니다. 요소 노드와 텍스트 (공백 포함) 만 고려됩니다. 주석 또는 처리 지침은 요소가 비어 있는지 여부에 영향을주지 않습니다.

Ctrl-a는 텍스트를 삭제하지만 하위 div는 그대로 둡니다. 자바 스크립트를 추가하여이 문제를 해결할 수 있습니다.


반복하는 것 같은 느낌인데, 왜 contenteditable요소 변이 를 확인하지 않나요? 콘텐츠를 변경하는 이벤트에 모든 것을 묶으려는 시도는 고통 스럽습니다. 버튼을 추가 (예 : 붙여 넣기)하거나 콘텐츠를 동적으로 변경 (JavaScript)해야하는 경우 어떻게해야합니까? 내 접근 방식은 MutationObservers를 사용하는 것 입니다. 데모 바이올린

HTML :

<div class="test" id="test" placeholder="Type something..." contenteditable="true"></div>

CSS :

.test {
    width: 500px;
    height: 70px;
    background: #f5f5f5;
    border: 1px solid #ddd;
    padding: 5px;
}

.test[placeholder]:empty:before {
    content: attr(placeholder);
    color: #555; 
}

자바 스크립트 :

var target = document.querySelector('#test');
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
      if (target.textContent == '') {
          target.innerHTML = '';
      }
  });    
});
var config = { attributes: true, childList: true, characterData: true };
observer.observe(target, config);

Christian Brink의 답변을 업데이트하면 더 많은 이벤트를 확인할 수 있습니다. 다음을 수행하면됩니다.

// More descriptive name
var $input = $(".placeholder");
function clearPlaceHolder() {
  if ($input.text().length == 0) {
    $input.empty();
    }
  }

// On each click
$input.keyup(clearPlaceHolder);

// Probably not needed, but just in case
$input.click(clearPlaceHolder);

// Copy/paste/cut events http://stackoverflow.com/q/17796731
$input.bind('input', (clearPlaceHolder));

// Other strange events (javascript modification of value?)
$input.change(clearPlaceHolder);

마지막으로 업데이트 된 JSFiddle


HTML 및 CSS로 라이브 데모 "콘텐츠 편집 가능한 div의 자리 표시 자"를 만들었습니다.
또한 Codepen : https://codepen.io/fritx/pen/NZpbqW
참조 : https://github.com/fritx/vue-at/issues/39#issuecomment-504412421

.editor {
  border: solid 1px gray;
  width: 300px;
  height: 100px;
  padding: 6px;
  overflow: scroll;
}
[contenteditable][placeholder]:empty:before {
  content: attr(placeholder);
  position: absolute;
  color: gray;
  background-color: transparent;
}
<textarea class="editor"
  placeholder="Textarea placeholder..."
></textarea>
<br/>
<br/>
<div class="editor"
  contenteditable
  placeholder="Div placeholder..."
  oninput="if(this.innerHTML.trim()==='<br>')this.innerHTML=''"
></div>


As swifft said, you can fix this with some super simple JS. Using jQuery:

var $input = $(".test");
$input.keyup(function () {
    if ($input.text().length == 0) {
        $input.empty();
    }
});

On each keystroke it checks whether there's any input text present. If not, it whacks any child elements that may have been left behind by user interaction with the element -- e.g. the <div> swifft describes.


I have this function, and I always use to prevent this kind of things.

I use my function in this way:

var notEmpty = {}

    notEmpty.selector = ".no-empty-plz"
    notEmpty.event = "focusout"
    notEmpty.nonEmpty = "---"


    neverEmpty(notEmpty)

And I just add the no-empty-plz to the Elements I that don't want to be empty.

/**
     * Used to prevent a element have a empty content, made to be used 
when we want to edit the content directly with the contenteditable=true 
because when a element is completely empty, it disappears U_U
     * 
     * @param selector
     * @param event
     * @param nonEmpty:
     *        String to be put instead empty
     */
function neverEmpty(params) {

    var element = $(params.selector)



    $(document).on(params.event, params.selector, function() {

        var text = $(this).html()
        text = hardTrim(text)

        if ($.trim(text)  == "") {
            $(this).html(params.nonEmpty)
        }
    });
}

params is actually a json, so selector = params.selector as you can see

And hardTrim is also another fucntion I created is like a trim but includs &nbsp and <br/>, etc

function hardTrim(text) {

    if (!exists(text)) {
        return ""
    }
    text = text.replace(/^\&nbsp\;|<br?\>*/gi, "").replace(/\&nbsp\;|<br?\>$/gi, "").trim();

    return text
}

<div id="write_comment" contenteditable="true"></div>

var placeholderCommentText = 'Comment...',
    placeholderComment = $('#write_comment').attr('placeholder', placeholderCommentText);

$('#write_comment').text(placeholderCommentText);

$('[contenteditable]').bind({
    focus: function(){
        if ($('#write_comment').text().length == 0 || $('#write_comment').text() == $('#write_comment').attr('placeholder')) {
            $(this).empty();
        }
        $(this).keyup(function(){
            if ($('#write_comment').text() == $('#write_comment').attr('placeholder')){
                $('#write_comment').attr('placeholder','');
            } else if ($('#write_comment').text().length == 0 ) {
                $('#write_comment').attr('placeholder', placeholderCommentText);
            }
        });
    },
    focusout: function(){
        if ($('#write_comment').text().length == 0) { 
            $(this).text($(this).attr('placeholder'));
        }
    }
});

ReferenceURL : https://stackoverflow.com/questions/20726174/placeholder-for-contenteditable-div

반응형