contentEditable에 placeholder 적용하기(흉내내기)

ahyes·2023년 9월 21일
0

contentEditable에서 placeholder를 적용하려면..

<div contentEditable='true' placeholder="'/'를 입력해 명령어 사용"></div>

위의 코드와 같은 방식으로 작성했을때 과연 아래의 사진과 같은 결과가 나올까요?

직접 해봤다면 원하는대로 적용이 되지않음을 알 수 있습니다.

placeholder는 input이나 textarea 태그인 경우에만 사용할 수 있습니다.

따라서 ContentEditable은 엘리먼트를 input처럼 편집할 수 있지만 placeholder 어트리뷰트는 적용할 수 없음을 알 수 있습니다. 그렇다면 placeholder를 사용할 수 있는 방법은 없는걸까요..?😭

가능합니다!

가상클래스를 이용한 방법으로 placeholder인것 처럼 동작할 수 있게 만들 수 있는데 방법은 아래와 같습니다.

  • :empty : 자식, 텍스트가 없는 요소 선택
  • :before : 의사 요소를 해당 선택자의 자식으로 생성 - 주로 content와 함께 사용됨
<ContentEditable
  className="Block"
  css={editable}
  placeholder="'/'를 입력해 명령어 사용"
  innerRef={this.contentEditable}
  html={this.state.html}
  tagName={this.state.tag}
  onChange={this.onChangeHandler}
  onKeyDown={this.onKeyDownHandler}/>
  1. placeholder를 먼저 만들어 원하는 메시지를 넣는다.
  2. 아래의 css코드를 적절하게 적용시킨다.
&:empty:before,
&:focus:empty:before { /* focus 되어있을 때로 plceholder가 보이도록 추가해주자. */
  content: attr(placeholder);
  color: gray  
}
profile
티스토리로 이사갑니다. https://useyhnha.tistory.com/

0개의 댓글