<style>
.toolTip{
width:400px;
height:40px;
background-color: orange;
padding: 8px;
box-sizing : border-box;
}
.toolTip button{
height:24px;
border:2px solid black;
background-color : white;
cursor : pointer;
}
.toolTip button:hover{
background-color:gray;
}
.editor{
margin-top : 10px;
width:600px;
height:600px;
padding:16px;
font-size:20px;
border:1px solid black;
}
</style>
<body>
<div class="toolTip">
<button class="bold">bold</button>
<button class="italic">italic</button>
<button class="align-left">align-left</button>
<button class="align-center">align-center</button>
<button class="align-right">align-right</button>
</div>
<div class="editor" contenteditable="true"></div>
<script>
(()=>{
document.querySelector('.bold').addEventListener('click',()=>{
document.execCommand('bold');
});
document.querySelector('.italic').addEventListener('click',()=>{
document.execCommand('italic');
})
document.querySelector('.align-left').addEventListener('click',()=>{
document.execCommand('justifyLeft');
})
document.querySelector('.align-center').addEventListener('click',()=>{
document.execCommand('justifyCenter');
})
document.querySelector('.align-right').addEventListener('click',()=>{
document.execCommand('justifyRight');
})
})()
</script>
</body>
해당 버튼이 추가될 때마다 기하급수적으로 js 코드가 증가함
<style>
.toolTip{
width:400px;
height:40px;
background-color: orange;
padding: 8px;
box-sizing : border-box;
}
.toolTip button{
height:24px;
border:2px solid black;
background-color : white;
cursor : pointer;
}
.toolTip button:hover{
background-color:gray;
}
.editor{
margin-top : 10px;
width:600px;
height:600px;
padding:16px;
font-size:20px;
border:1px solid black;
}
</style>
<body>
<div class="toolTip">
<button data-command="bold">bold</button>
<button data-command="italic">italic</button>
<button data-command="justifyLeft">align-left</button>
<button data-command="justifyCenter">align-center</button>
<button data-command="justifyRight">align-right</button>
</div>
<div class="editor" contenteditable="true"></div>
<script>
(()=>{
document.querySelectorAll('.toolTip button').forEach(dom=>{
dom.addEventListener('click',(e)=>{
const attr = e.target.getAttribute('data-command');
document.execCommand(attr);
})
})
})()
</script>
</body>
이를 통해 js코드는 따로 더 추가 할 필요없이
data-command
의 속성 값이 적용되어 처리하면 된다.