Programing

contenteditable의 자리 표시 자-포커스 이벤트 문제

lottogame 2020. 11. 29. 09:33
반응형

contenteditable의 자리 표시 자-포커스 이벤트 문제


나는 버그가 발생하는 작업 예제를 설명 / 증명하지 않고 전에이 질문을 시도해 왔습니다. 그래서 여기 또 다른 시도가 있습니다.

콘텐츠 편집 가능한 DIV에 자리 표시 자 효과를 복제하려고합니다. 핵심 개념은 간단합니다.

<div contenteditable><em>Edit me</em></div>

<script>
$('div').focus(function() {
    $(this).empty();
});
</script>

일부 작업은 작동 할 수 있지만 자리 표시 자에 HTML이 포함되어 있거나 다른 처리가 수행되는 경우 편집 가능한 DIV의 텍스트 캐럿이 제거되고 사용자는 입력을 시작할 수 있도록 편집 가능한 DIV를 다시 클릭해야합니다. 여전히 초점) :

예 : http://jsfiddle.net/hHLXr/6/

이벤트 루프를 생성하기 때문에 핸들러에서 포커스 트리거를 사용할 수 없습니다. 따라서 편집 가능한 DIV에서 캐럿 커서를 다시 설정하거나 다른 방법으로 초점을 다시 설정하는 방법이 필요합니다.


선택 사항을 수동으로 업데이트해야 할 수도 있습니다. IE에서는 포커스 이벤트가 너무 늦기 때문에 activate대신 이벤트를 사용하는 것이 좋습니다 . 다음은 IE <= 8을 포함한 모든 주요 브라우저에서 작업을 수행하는 일부 코드입니다 (CSS 전용 대안은 그렇지 않음).

라이브 데모 : http://jsfiddle.net/hHLXr/12/

암호:

$('div').on('activate', function() {
    $(this).empty();
    var range, sel;
    if ( (sel = document.selection) && document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(this);
        range.select();
    }
});

$('div').focus(function() {
    if (this.hasChildNodes() && document.createRange && window.getSelection) {
        $(this).empty();
        var range = document.createRange();
        range.selectNodeContents(this);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
});

다음은 다른 답변 중 일부를 보완하는 CSS 전용 솔루션입니다.

<div contentEditable=true data-ph="My Placeholder String"></div>
<style>
    [contentEditable=true]:empty:not(:focus)::before{
        content:attr(data-ph)
    }
</style>

편집 : 여기에 내 코드 조각이 있습니다-> http://codepen.io/mrmoje/pen/lkLez

EDIT2 :이 방법은 <br>a select-all-cut또는 select-all-delete모든 라인을 수행 한 후 div에 잔류 요소가 존재 하기 때문에 다중 라인 애플리케이션에 대해 100 % 작동하지 않습니다 . 크레딧 :-@vsync
백 스페이스가 제대로 작동하는 것 같습니다 (적어도 웹킷 / 깜박임에서)


난 그냥 한 이에 대한 플러그인을 발표했다 .

CSS3와 JavaScript의 조합을 사용하여의 내용에 추가하지 않고 자리 표시자를 표시합니다 div.

HTML :

<div contenteditable='true' data-placeholder='Enter some text'></div>

CSS :

div[data-placeholder]:not(:focus):not([data-div-placeholder-content]):before {
    content: attr(data-placeholder);
    float: left;
    margin-left: 5px;
    color: gray;
}

JS :

(function ($) {
    $('div[data-placeholder]').on('keydown keypress input', function() {
        if (this.textContent) {
            this.dataset.divPlaceholderContent = 'true';
        }
        else {
            delete(this.dataset.divPlaceholderContent);
        }
    });
})(jQuery);

그리고 그게 다야.


CSS 의사 클래스를 사용하십시오.

span.spanclass:empty:before {content:"placeholder";}

이를 수행하는 가장 좋은 방법은 placeholder평소와 같이 속성 을 사용하고 CSS 몇 줄을 추가하는 것입니다.

HTML

<div contenteditable placeholder="I am a placeholder"></div>

CSS

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

참고 : CSS :empty선택기는 여는 태그와 닫는 태그 사이에 문자 그대로 아무것도없는 경우에만 작동합니다. 여기에는 새 줄, 탭, 빈 공간 등이 포함됩니다.

Codepen


이 작은 솔루션 만 있으면됩니다.

[contenteditable=true]:empty:before{
  content: attr(placeholder);
  display: block; /* For Firefox */
}

데모 : http://codepen.io/flesler/pen/AEIFc


제 방법은 다음과 같습니다

. jQuery와 CSS3의 조합을 사용합니다. html5 자리 표시 자 속성과 똑같이 작동합니다! .

  • Hides itself right away when you input the first letter
  • Shows itself again when you delete what you input into it

HTML:

<div class="placeholder" contenteditable="true"></div>

CSS3:

.placeholder:after {
    content: "Your placeholder"; /* this is where you assign the place holder */
    position: absolute;
    top: 10px;
    color: #a9a9a9;
}

jQuery:

$('.placeholder').on('input', function(){
    if ($(this).text().length > 0) {
        $(this).removeClass('placeholder');
    } else {
        $(this).addClass('placeholder');
    }
});

DEMO: http://jsfiddle.net/Tomer123/D78X7/


Here's the fix that I used.

<div contenteditable><em>Edit me</em></div>
<script>
$('div').focus(function() {
    var target = $(this);
    window.setTimeout(function() { target.empty(); }, 10);
});
</script>

I developed a jQuery plug-in for this. Take a look https://github.com/phitha/editableDiv


var curText = 'Edit me';
$('div').focusin(function() {
    if ($(this).text().toLowerCase() == curText.toLowerCase() || !$(this).text().length) {
        $(this).empty();
    }
}).focusout(function() {
    if ($(this).text().toLowerCase() == curText.toLowerCase() || !$(this).text().length) {
        $(this).html('<em>' + curText + '</em>');
    }
});

This is not exact solution of your problem ..

in summernote options set

airMode:true

placeholder works in this way.

참고URL : https://stackoverflow.com/questions/9093424/placeholder-in-contenteditable-focus-event-issue

반응형