반응형
| 테이블 <td> 긴 텍스트, 깔끔하게 표시하고 툴팁으로 전체 보기
테이블(<table>)을 만들다 보면 <td> 안에 들어가는 텍스트 내용이 너무 길어 화면 레이아웃을 깨뜨리거나 가독성을 해치는 경우가 많습니다. 이럴 때 긴 텍스트를 한 줄로 줄이고 말줄임표(...)로 처리한 뒤, 마우스를 올리면 전체 내용을 보여주는 툴팁 기능을 추가하여 UI를 깔끔하게 유지할 수 있습니다.
이번 포스팅에서는 CSS와 jQuery를 활용하여 이 기능을 구현하는 방법을 자세히 알아보겠습니다.
1. 목표 설정
<td>내 긴 텍스트를 한 줄로 표시하고, 넘치는 부분은...으로 처리- 마우스를
<td>에 올렸을 때,...으로 잘린 텍스트의 전체 내용을 툴팁으로 보여주기
2. CSS로 텍스트 말줄임표 처리하기
가장 먼저 할 일은 CSS를 사용하여 긴 텍스트를 한 줄로 만들고 말줄임표로 표시하는 것입니다. 이 기능은 white-space, overflow, text-overflow 속성을 조합하여 구현합니다. 이때, <td> 자체에 직접 적용하기보다는 <td> 안에 <div>나 <span> 요소를 하나 더 넣고 그 요소에 CSS 클래스를 적용하는 것이 더 유연하고 안정적입니다.
HTML 구조 예시:
<table>
<thead>
<tr>
<th>상품명</th>
<th>설명</th>
<th>수량</th>
</tr>
</thead>
<tbody>
<tr>
<td>신제품 A</td>
<td class="has-custom-tooltip">
<div class="truncate-text" data-full-text="이 상품은 최신 기술이 적용되어 매우 뛰어난 성능을 자랑합니다. 사용자 편의성을 극대화하여 누구나 쉽게 사용할 수 있으며, 디자인 또한 훌륭합니다.">
이 상품은 최신 기술이 적용되어 매우 뛰어난 성능을 자랑합니다. 사용자 편의성을 극대화하여 누구나 쉽게 사용할 수 있으며, 디자인 또한 훌륭합니다.
</div>
</td>
<td>100</td>
</tr>
<tr>
<td>구형 B</td>
<td class="has-custom-tooltip">
<div class="truncate-text" data-full-text="기존 모델로, 기본적인 기능에 충실하여 꾸준한 사랑을 받고 있습니다.">
기존 모델로, 기본적인 기능에 충실하여 꾸준한 사랑을 받고 있습니다.
</div>
</td>
<td>50</td>
</tr>
</tbody>
</table>
CSS 코드:
/* 긴 텍스트를 한 줄로 줄이고 ...으로 표시하는 스타일 */
.truncate-text {
white-space: nowrap; /* 텍스트 줄바꿈 방지 */
overflow: hidden; /* 넘치는 내용 숨김 */
text-overflow: ellipsis; /* 숨겨진 내용 ...으로 표시 */
max-width: 250px; /* (필수) 텍스트가 잘릴 기준 너비 지정. 실제 td 너비에 맞춰 조정 */
display: block; /* max-width가 작동하도록 block 또는 inline-block 설정 */
}
white-space: nowrap;: 텍스트가 아무리 길어도 줄 바꿈 없이 한 줄에 계속 표시됩니다.overflow: hidden;: 컨테이너(div.truncate-text)를 넘어가는 내용은 보이지 않게 숨겨집니다.text-overflow: ellipsis;:overflow: hidden과white-space: nowrap이 적용된 상태에서 넘치는 텍스트를...으로 대체합니다.max-width: 이 속성이 없으면text-overflow: ellipsis가 제대로 작동하지 않을 수 있습니다.<div>의 최대 너비를 명시적으로 지정하여 텍스트가 언제 잘릴지 기준을 설정합니다.
3. jQuery로 커스텀 툴팁 구현하기
CSS만으로는 ...이 표시된 텍스트의 전체 내용을 마우스 호버 시 보여주는 기능까지는 구현하기 어렵습니다. 브라우저의 기본 title 속성을 사용할 수도 있지만 (별도 JS 없이 title="전체 텍스트" 추가), 더 유연한 디자인과 위치 제어를 위해 jQuery를 이용한 커스텀 툴팁을 만드는 것이 좋습니다.
HTML에 툴팁 요소 추가:
<div id="custom-tooltip"></div>
커스텀 툴팁을 위한 CSS:
/* 커스텀 툴팁 스타일 */
#custom-tooltip {
position: absolute; /* 절대 위치로 다른 요소 위에 띄움 */
background-color: #333; /* 어두운 배경색 */
color: white; /* 밝은 글자색 */
padding: 8px 12px; /* 적절한 패딩 */
border-radius: 4px; /* 모서리 둥글게 */
box-shadow: 0 2px 5px rgba(0,0,0,0.3); /* 은은한 그림자 */
display: none; /* 초기에는 숨김 */
z-index: 9999; /* 다른 요소들보다 위에 표시되도록 높은 z-index */
max-width: 400px; /* 툴팁의 최대 너비 지정 */
word-wrap: break-word; /* 툴팁 내용이 길면 자동으로 줄바꿈 */
font-size: 14px; /* 글자 크기 */
line-height: 1.4; /* 줄 간격 */
}
jQuery 코드:
$(document).ready(function() {
// 툴팁으로 사용될 HTML 요소 선택
const $customTooltip = $('#custom-tooltip');
// .has-custom-tooltip 클래스를 가진 td 내의 .truncate-text div에 이벤트 바인딩
$('.has-custom-tooltip .truncate-text').on({
// 마우스가 요소 위로 들어올 때
mouseenter: function(e) {
// data-full-text 속성에서 전체 텍스트를 가져옴
const fullText = $(this).data('full-text');
// 툴팁에 내용 설정
$customTooltip.text(fullText);
// 툴팁 위치 계산 (마우스 커서 근처에 표시되도록)
// e.pageX, e.pageY는 마우스 커서의 현재 위치입니다.
// 툴팁이 화면의 오른쪽이나 아래쪽 경계를 넘어가지 않도록 간단한 조정 로직을 추가할 수 있습니다.
let tooltipX = e.pageX + 15; // 마우스 커서에서 오른쪽으로 15px 떨어진 위치
let tooltipY = e.pageY + 15; // 마우스 커서에서 아래쪽으로 15px 떨어진 위치
// 툴팁이 화면 오른쪽 경계를 넘어가는 경우 조정
if (tooltipX + $customTooltip.outerWidth() > $(window).width()) {
tooltipX = e.pageX - $customTooltip.outerWidth() - 15;
}
// 툴팁이 화면 아래쪽 경계를 넘어가는 경우 조정
if (tooltipY + $customTooltip.outerHeight() > $(window).height() + $(window).scrollTop()) {
tooltipY = e.pageY - $customTooltip.outerHeight() - 15;
}
// 계산된 위치로 툴팁을 이동시키고 보이게 함
$customTooltip.css({
left: tooltipX,
top: tooltipY
}).show();
},
// 마우스가 요소 위에서 움직일 때 (툴팁이 마우스를 따라다니게 하려면)
mousemove: function(e) {
let tooltipX = e.pageX + 15;
let tooltipY = e.pageY + 15;
if (tooltipX + $customTooltip.outerWidth() > $(window).width()) {
tooltipX = e.pageX - $customTooltip.outerWidth() - 15;
}
if (tooltipY + $customTooltip.outerHeight() > $(window).height() + $(window).scrollTop()) {
tooltipY = e.pageY - $customTooltip.outerHeight() - 15;
}
$customTooltip.css({
left: tooltipX,
top: tooltipY
});
},
// 마우스가 요소 밖으로 벗어날 때
mouseleave: function() {
$customTooltip.hide(); // 툴팁 숨기기
}
});
});
4. 전체 코드 예시 (index.html 또는 유사 파일)
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>테이블 긴 텍스트 툴팁 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
/* 긴 텍스트를 한 줄로 줄이고 ...으로 표시하는 스타일 */
.truncate-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 250px; /* 적절한 너비로 조정 */
display: block;
}
/* 커스텀 툴팁 스타일 */
#custom-tooltip {
position: absolute;
background-color: #333;
color: white;
padding: 8px 12px;
border-radius: 4px;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
display: none;
z-index: 9999;
max-width: 400px;
word-wrap: break-word;
font-size: 14px;
line-height: 1.4;
}
</style>
</head>
<body>
<h1>테이블 긴 텍스트 툴팁 예제</h1>
<table>
<thead>
<tr>
<th>상품명</th>
<th>설명</th>
<th>수량</th>
</tr>
</thead>
<tbody>
<tr>
<td>신제품 A</td>
<td class="has-custom-tooltip">
<div class="truncate-text" data-full-text="이 상품은 최신 기술이 적용되어 매우 뛰어난 성능을 자랑합니다. 사용자 편의성을 극대화하여 누구나 쉽게 사용할 수 있으며, 디자인 또한 훌륭합니다. 이 긴 문장은 테스트를 위해 충분히 길게 작성되었습니다.">
이 상품은 최신 기술이 적용되어 매우 뛰어난 성능을 자랑합니다. 사용자 편의성을 극대화하여 누구나 쉽게 사용할 수 있으며, 디자인 또한 훌륭합니다. 이 긴 문장은 테스트를 위해 충분히 길게 작성되었습니다.
</div>
</td>
<td>100</td>
</tr>
<tr>
<td>구형 B</td>
<td class="has-custom-tooltip">
<div class="truncate-text" data-full-text="기존 모델로, 기본적인 기능에 충실하여 꾸준한 사랑을 받고 있습니다.">
기존 모델로, 기본적인 기능에 충실하여 꾸준한 사랑을 받고 있습니다.
</div>
</td>
<td>50</td>
</tr>
<tr>
<td>신형 C</td>
<td class="has-custom-tooltip">
<div class="truncate-text" data-full-text="이 제품은 혁신적인 배터리 기술을 적용하여 사용 시간을 대폭 늘렸습니다. 야외 활동이나 장시간 사용에 최적화되어 있으며, 가벼운 무게로 휴대성이 뛰어납니다. 새로운 사용자 경험을 제공할 것입니다.">
이 제품은 혁신적인 배터리 기술을 적용하여 사용 시간을 대폭 늘렸습니다. 야외 활동이나 장시간 사용에 최적화되어 있으며, 가벼운 무게로 휴대성이 뛰어납니다. 새로운 사용자 경험을 제공할 것입니다.
</div>
</td>
<td>75</td>
</tr>
</tbody>
</table>
<div id="custom-tooltip"></div>
<script>
$(document).ready(function() {
const $customTooltip = $('#custom-tooltip');
$('.has-custom-tooltip .truncate-text').on({
mouseenter: function(e) {
const fullText = $(this).data('full-text');
$customTooltip.text(fullText);
let tooltipX = e.pageX + 15;
let tooltipY = e.pageY + 15;
if (tooltipX + $customTooltip.outerWidth() > $(window).width()) {
tooltipX = e.pageX - $customTooltip.outerWidth() - 15;
}
if (tooltipY + $customTooltip.outerHeight() > $(window).height() + $(window).scrollTop()) {
tooltipY = e.pageY - $customTooltip.outerHeight() - 15;
}
$customTooltip.css({
left: tooltipX,
top: tooltipY
}).show();
},
mousemove: function(e) {
let tooltipX = e.pageX + 15;
let tooltipY = e.pageY + 15;
if (tooltipX + $customTooltip.outerWidth() > $(window).width()) {
tooltipX = e.pageX - $customTooltip.outerWidth() - 15;
}
if (tooltipY + $customTooltip.outerHeight() > $(window).height() + $(window).scrollTop()) {
tooltipY = e.pageY - $customTooltip.outerHeight() - 15;
}
$customTooltip.css({
left: tooltipX,
top: tooltipY
});
},
mouseleave: function() {
$customTooltip.hide();
}
});
});
</script>
</body>
</html>
반응형
'📕 Programing > jQuery' 카테고리의 다른 글
| id="excelGo" 버튼을 클릭했을 때 Excel 파일다운로드 (2) | 2025.07.18 |
|---|---|
| 마우스 로딩표시 (0) | 2023.12.26 |
| [jQuery] match() 함수(특정 문자 포함 여부) (0) | 2023.02.09 |
| [jQuery] checkbox에 체크된 값들만 가져오기 / 전체 선택|해제 (0) | 2023.02.03 |
| [jQuery Plugin ] magnify - 이미지 확대 | 축소 등 (0) | 2021.10.18 |