반응형

스크립트로 이미지 태그를 추가히기 위해서는 html 로 img 태그를 만들어 추가하는 방법도 있지만 execCommand 를 추가하는 방법도 있습니다. execCommand 는 성공/실패 여부를 true/false 로 return 해줍니다.

document.execCommand("insertImage", false, img url);

위 방법이 여의치 않은 경우 appendChild 를 통하여 추가하는 방법도 있습니다.

var img = document.createElement("img");
img.src = "img url";

var targetElement = document.getElementById("parent");
targetElement.appendChild(img);

 

하지만 appendChild 를 사용하게 되면 부모 Element 기준으로 마지막 자식으로 들어가게 됩니다.

그러면 아래와 같이 텍스트 사이에 이미지를 추가하고 싶은 경우는 사용할 수 없습니다.

<body>
	<div contentseditable='true' id='targetElement'>
    	img insert [여기에 이미지 추가하고 싶음] test
    </div>
</body>

이 경우에는 현재 focus (selection) 가 위치한 곳을 찾아 추가해 줄 수 있습니다.

var selection = document.getSelection();

if(selection.focusNode.nodeType == 1){
	//현재 선택된 위치가 태그인 경우는 위치를 알 필요 없이 그냥 뒤에 넣음
	selection.appendChild(img); //img tag 는 위에서 만듬. 참고
} else {
	//현재 선택된 위치가 text중간인 경우
    var at = selection.anchorOffset;
    var sa = selection.anchorNode;
    sa.parentNode.insertBefore(img, sa.splitText(at));
}

위 코드는 제 케이스에 맞는 코드 이므로 참고만 해서 필요한 방법으로 구현해야 합니다.!!!

반응형

+ Recent posts