- JAVASCRIPT
- 해쉬태그 코드
- 댓글 : 0건
- 글쓴이 : mrhmh
- 작성일 : 2025-10-14 09:06
- 조회수 : 162
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<style>
.view-tag {
display: inline-block;
background-color: #eee;
border-radius: 5px;
padding: 5px 10px;
margin-right: 5px;
font-size: 14px;
color: #333;
}
.tag-container {
display: flex;
flex-wrap: wrap;
gap: 5px;
padding: 5px;
border: 1px solid #ccc;
border-radius: 3px;
background: #fff;
}
.tag {
background-color: #eee;
border-radius: 15px;
padding: 5px 10px;
font-size: 14px;
color: #333;
display: inline-block;
}
.tag-input {
border: none;
outline: none;
flex: 1;
min-width: 120px;
height:30px;
}
<div class="write_div">
<div class="tag-container" id="tagContainer">
<input type="text" id="tagInput" class="tag-input" value="<?php echo $write['wr_1'] ?>" placeholder="#해시태그 입력">
</div>
<input type="hidden" name="wr_1" id="wr_1" value="<?php echo $write['wr_1'] ?>">
</div>
<script>
$(function() {
const availableTags = ["#여행", "#맛집", "#일상", "#운동", "#코딩", "#사진", "#산책", "#강아지"];
function createTag(text) {
const tag = $('<span class="tag"></span>').text(text);
tag.on('click', function() {
$(this).remove();
updateHiddenInput();
});
return tag;
}
function updateHiddenInput() {
const tags = [];
$("#tagContainer .tag").each(function() {
tags.push($(this).text());
});
$("#wr_1").val(tags.join(' '));
}
function loadInitialTags() {
const initial = $("#wr_1").val();
if (initial) {
const tagList = initial.split(' ');
tagList.forEach(tag => {
if (tag.startsWith("#")) {
$("#tagContainer").append(createTag(tag)); // append로 순서 유지
}
});
}
}
$("#tagInput").autocomplete({
source: availableTags,
minLength: 1,
select: function(event, ui) {
const tagText = ui.item.value;
$("#tagContainer").append(createTag(tagText));
$(this).val('');
updateHiddenInput();
return false;
}
});
$("#tagInput").on("keydown", function(e) {
const val = $(this).val().trim();
if ((e.key === " " || e.key === "Enter") && val.startsWith("#") && val.length > 1) {
e.preventDefault();
$("#tagContainer").append(createTag(val));
$(this).val('');
updateHiddenInput();
}
if (e.key === "Backspace" && val === "") {
const lastTag = $("#tagContainer .tag").last();
if (lastTag.length) {
lastTag.remove();
updateHiddenInput();
}
}
});
loadInitialTags();
});
</script>
댓글목록
등록된 댓글이 없습니다.