[jQuery] 테이블(TABLE) 행(ROW) 순서위치 이동시키기[jQuery] 테이블(TABLE) 행(ROW) 순서위치 이동시키기

Posted at 2018. 3. 22. 14:01 | Posted in JavaScript & jQuery/jQuery
반응형




참고 : http://ktsmemo.cafe24.com/s/jQueryTip/64




■ 테이블 행(ROW) 위치 이동시키기




# 소스코드

<html>

<head>

<title>:: 테이블 행(ROW) 위치 이동하기 ::</title>

<script src="http://code.jquery.com/jquery-1.12.4.js"></script>

<script type="text/javascript">

function checkeRowColorChange(obj) {

// 체크된 라디오 박스의 행(row)에 강조색깔로 바꾸기 전 모든 행(row)의 백그라운드를 흰색으로 변경한다.

jQuery("#girlTbody > tr").css("background-color", "#FFFFFF");


// 체크된 라디오 박스의 행이 몇번째에 위치하는지 파악한다.

var row = jQuery(".chkRadio").index(obj);


// 체크된 라디오 박스의 행(row)의 색깔을 변경한다.

jQuery("#girlTbody > tr").eq(row).css("background-color", "#FAF4C0");

}


function rowMoveEvent(direction) {

// 체크된 행(row)의 존재 여부를 파악한다.

if(jQuery(".chkRadio:checked").val()) {


// 체크된 라디오 박스의 행(row)을 변수에 담는다.

var row = jQuery(".chkRadio:checked").parent().parent();


                // 체크된 행(row)의 이동 한계점을 파악하기 위해 인덱스를 파악한다.

var num = row.index();


// 전체 행의 개수를 구한다.

var max = (jQuery(".chkRadio").length - 1); // index는 0부터 시작하기에 -1을 해준다.


if(direction == "up") {


if(num == 0) { 


// 체크된 행(row)의 위치가 최상단에 위치해 있을경우 더이상 올라갈 수 없게 막는다.

alert("첫번째로 지정되어 있습니다.\n더이상 순서를 변경할 수 없습니다.");

return false;

} else {


// 체크된 행(row)을 한칸 위로 올린다.

row.prev().before(row);

}

} else if(direction == "down") {


if(num >= max) {


// 체크된 행(row)의 위치가 최하단에 위치해 있을경우 더이상 내려갈 수 없게 막는다.

alert("마지막으로 지정되어 있습니다.\n더이상 순서를 변경할 수 없습니다.");

return false;

} else {


// 체크된 행(row)을 한칸 아래로 내린다.

row.next().after(row);

}

}


} else {

alert("선택된 행이 존재하지 않습니다\n위치를 이동시킬 행을 하나 선택해 주세요.");

}

}

</script>

</head>

<body>

<table border="1" cellspacing="0">

<thead style="background-color:#000080;font-weight:bold;color:#FFFFFF;">

<tr>

<th style="width:30px;"></th>

<th style="width:100px;">:: 가수 ::</th>

<th style="width:300px;">:: 노래 제목 ::</th>

<th style="width:100px;">:: 발매일 ::</th>

</tr>

</thead>

<tbody id="girlTbody" style="text-align:center;">

<tr>

<td><input type="radio" class="chkRadio" name="chkRadio" onClick="checkeRowColorChange(this);"></td>

<td>트와이스</td>

<td style="text-align:left;">하트 쉐이커(Heart Shaker)</td>

<td>2017-12-11</td>

</tr>

<tr>

<td><input type="radio" class="chkRadio" name="chkRadio" onClick="checkeRowColorChange(this);"></td>

<td>레드벨벳</td>

<td style="text-align:left;">빨간 맛(Red Flavor)</td>

<td>2017-07-09</td>

</tr>

<tr>

<td><input type="radio" class="chkRadio" name="chkRadio" onClick="checkeRowColorChange(this);"></td>

<td>러블리즈</td>

<td style="text-align:left;">종소리(Twinkle)</td>

<td>2017-11-14</td>

</tr>

<tr>

<td><input type="radio" class="chkRadio" name="chkRadio" onClick="checkeRowColorChange(this);"></td>

<td>모모랜드</td>

<td style="text-align:left;">뿜뿜(BBoomBBoom)</td>

<td>2018-01-03</td>

</tr>

<tr>

<td><input type="radio" class="chkRadio" name="chkRadio" onClick="checkeRowColorChange(this);"></td>

<td>여자친구</td>

<td style="text-align:left;">귀를 기울이면(Love Whisper)</td>

<td>2017-08-01</td>

</tr>

</tbody>

<tfoot style="background-color:#A9A9A9;">

<tr>

<td colspan="4" style="text-align:center;">

<input type="button" onClick="rowMoveEvent('up');" value="▲" style="width:50px;"/>

&nbsp;&nbsp;

<input type="button" onClick="rowMoveEvent('down');" value="▼" style="width:50px;"/>

</td>

</tr>

</tfoot>

</table>

</body>

</html> 




# 출력결과





반응형
//

[jQuery] 쇼핑몰 대표 이미지 상품박스[jQuery] 쇼핑몰 대표 이미지 상품박스

Posted at 2018. 3. 14. 09:34 | Posted in JavaScript & jQuery/jQuery
반응형




■ onMouseover를 통한 이미지 변경




# 소스코드

<html>
<title>:: 상품박스 ::</title>
<head>
<style type="text/css">
    .represent {
        border:1px solid #FF0000;
        width:460px;
        overflow:auto;
    }

    ul {
        list-style:outside none none;
        margin:0;
        padding:0;
    }

    li {
        margin:0 0 0 0;
        padding:0 0 0 0;
        border:0;
        float:left;
        width:20%;
    }

    img {
        width:100%;
    }
</style>
</head>
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
function changeRepresentImage(num) {
    var link = jQuery(".imgServe").eq(num).attr("src");
    jQuery("#imgRepresent").attr("src", link);
}
</script>
<body>
    <div class="represent">
        <img id="imgRepresent" src="./image/Box_01.png" style="width:460px;height:460px;"/>
        <ul>
            <li>
                <a href="javascript:;" onMouseover="changeRepresentImage('0');">
                    <img class="imgServe" src="./image/Box_01.png"/>
                </a>
            </li>
            <li>
                <a href="javascript:;" onMouseover="changeRepresentImage('1');">
                    <img class="imgServe" src="./image/Box_02.png"/>
                </a>
            </li>
            <li>
                <a href="javascript:;" onMouseover="changeRepresentImage('2');">
                    <img class="imgServe" src="./image/Box_03.png"/>
                </a>
            </li>
            <li>
                <a href="javascript:;" onMouseover="changeRepresentImage('3');">
                    <img class="imgServe" src="./image/Box_04.png"/>
                </a>
            </li>
            <li>
                <a href="javascript:;" onMouseover="changeRepresentImage('4');">
                    <img class="imgServe" src="./image/Box_05.png"/>
                </a>
            </li>
        </ul>
    </div>
</body>
</html>



# 출력결과




인터넷 쇼핑몰등에서는 위와같이 상품의 대표이미지를 올려둘 수 있는 사이트들이 많이 있다.


이렇게 상품 이미지를 올리는것은


<input type="file"/>을 사용하는 것이 쉬울 수 있겠지만,


좀더 세련된 UI를 사용해 보기위해 아래와같은 방식을 취해 보려고 한다.







■ AJAX로 파일 업로드 하고 썸네일 이미지 받아오기




# 소스코드 - 이미지 업로드를 실제로 조작하는 thumbnail_upload.php

<html>
<title>:: 업로드 파일 썸네일 생성 ::</title>
<head>
<style type="text/css">
.temporaryFile {
    display:none;
}

.thumbnailImg {
    width:64px;
    height:64px;
    border-radius:10px;
    border:3px solid #CCCCCC;
}
</style>
</head>
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
// 이미지를 업로드 할 준비를 시작한다.
function temporaryFileUpload(num) {

    // 이미지파일의 정보를 받을 배열을 선언한다.
    var tmpFile = new Object();
    tmpFile['file'] = new Array();     // tmpFile['file'] 파일의 정보를 담을 변수
    tmpFile['img'] = new Array();    // tmpFile['file'] 이미지의 경로를 담을 변수
    var tmpNum = 0;
    var addPlus = 0;

    // 먼저 업로드 된 파일의 존재 유무를 확인한다.
    if(jQuery(".temporaryFile").eq(num).val()) {

        // 파일이 존재하면 우선 기존 파일을 삭제한 이후에 작업을 진행한다.
        if(confirm("해당 이미지를 삭제 하시겠습니까?") == true) {

            // 먼저 업로드 하지 않을 파일을 제거한다.
            jQuery(".temporaryFile").eq(num).val("");

            // 파일이 제거되면 <input type="file"/>의 수만큼 반복문을 돌린다.
            jQuery(".temporaryFile").each(function(idx) {

                // 반복문을 돌리는 중에 <input type="file"/>의 값이 존재한는 순서로 배열에 담는다.
                if(jQuery(".temporaryFile").eq(idx).val()) {
                    tmpFile['file'][tmpNum] = [jQuery(".temporaryFile").eq(idx).clone()];
                    tmpFile['img'][tmpNum] = jQuery(".thumbnailImg").eq(idx).attr("src");
                    tmpNum++;
                }
            });
          
            // 모든 썸네일 이미지 정보를 초기화 한다.
            jQuery(".temporaryFile").val("");
            jQuery(".thumbnailImg").attr("src", "./plusimg.png");
            jQuery(".thumbnailImg").css("display", "none");
          

            // 배열로 받은 파일의 정보를 for문 or for in문을 사용하여 순서를 재정렬한다.


            /* ① for in 문을 사용한 경우(for in 문을 주석처리 한 이유는 아래에 기술 하였다.)

            for(var key in tmpFile['file']) {
                jQuery(".temporaryFile").eq(key).replaceWith(tmpFile['file'][key][0].clone(true));
                jQuery(".thumbnailImg").eq(key).css("display", "inline");
                jQuery(".thumbnailImg").eq(key).attr("src", tmpFile['img'][key]);
                addPlus++;
            }

            */

           

            /* for 문(ie8 이하 호환)을 사용한 경우 */

            for(var lineUp = 0, item; item=tmpFiles['file'][lineUp]; lineUp++) {
                jQuery(".temporaryFile").eq(lineUp).replaceWith(tmpFiles['file'][addPlus][0].clone(true));
                jQuery(".thumbnailImg").eq(lineUp).css("display", "inline");
                jQuery(".thumbnailImg").eq(lineUp).attr("src", tmpFiles['src'][addPlus]);
                jQuery(".previousFile").eq(lineUp).val(tmpFiles['img'][addPlus]);
                addPlus++;
            }

            if(addPlus < 5) {
                jQuery(".thumbnailImg").eq(addPlus).css("display", "inline");
            }

        } else {
            return false;
        }
    }
  
    // 파일이 존재하지 않다면 업로드를 시작한다.
    else {
        jQuery(".temporaryFile").eq(num).click();
    }
}

// 임시폴더에 파일을 업로드하고 그 경로를 받아온다.
function temporaryFileTransmit(num) {
    var form = jQuery("#uploadFrom")[0];
    var formData = new FormData(form);
    formData.append("mode", "temporaryImageUpload");
    formData.append("tmpFile", jQuery(".temporaryFile").eq(num)[0].files[0]);
  
    // ajax로 파일을 업로드 한다.
    jQuery.ajax({
          url : "./upload_class.php"
        , type : "POST"
        , processData : false
        , contentType : false
        , data : formData
        , success:function(json) {
            var obj = JSON.parse(json);
            if(obj.ret == "succ") {

                // 업로드된 버튼을 임시폴더에 업로드된 경로의 이미지 파일로 교체한다.
                jQuery(".thumbnailImg").eq(num).attr("src", obj.img);

                // 업로드 버튼이 4개 이하인경우 업로드 버튼을 하나 생성한다.
                if(num < 5) {
                    jQuery(".thumbnailImg").eq(++num).css("display", "inline");
                }

            } else {
                alert(obj.message);
                return false;
            }
        }
    });
}
</script>
<body>
<form id="uploadFrom" method="post">
<input type="file" class="temporaryFile" name="thumbnailImg[0]" onChange="temporaryFileTransmit(0);" style="display:none;"/>
<input type="file" class="temporaryFile" name="thumbnailImg[1]" onChange="temporaryFileTransmit(1);" style="display:none;"/>
<input type="file" class="temporaryFile" name="thumbnailImg[2]" onChange="temporaryFileTransmit(2);" style="display:none;"/>
<input type="file" class="temporaryFile" name="thumbnailImg[3]" onChange="temporaryFileTransmit(3);" style="display:none;"/>
<input type="file" class="temporaryFile" name="thumbnailImg[4]" onChange="temporaryFileTransmit(4);" style="display:none;"/>
<h1># 이미지 파일 업로드시 썸네일 생성하기</h1>
<table>
    <tr>
        <th>이미지 업로드 : </th>
        <td>
            <a href="javascript:;" onClick="temporaryFileUpload(0);">
                <img class="thumbnailImg" src="./plusimg.png" style="display:inline;"/>
            </a>
            <a href="javascript:;" onClick="temporaryFileUpload(1);">
                <img class="thumbnailImg" src="./plusimg.png" style="display:none;"/>
            </a>
            <a href="javascript:;" onClick="temporaryFileUpload(2);">
                <img class="thumbnailImg" src="./plusimg.png" style="display:none;"/>
            </a>
            <a href="javascript:;" onClick="temporaryFileUpload(3);">
                <img class="thumbnailImg" src="./plusimg.png" style="display:none;"/>
            </a>
            <a href="javascript:;" onClick="temporaryFileUpload(4);">
                <img class="thumbnailImg" src="./plusimg.png" style="display:none;"/>
            </a>
        </td>
    </tr>
</table>
</form>
</body>
</html> 


※ for in 문을 주석 처리한 이유

 처음에 제작할때는 for in문을 사용했었다.
 그런데 문제가 발생한것이 필자는 평소 다음 오픈 에디터를 주로 사용하는데.
 다음 오픈 에디터와 같은 페이지에서 해당 반복문이 돌아갈 경우 스크립트 충돌이 발생했다.

 (이유는 아직 까지 확인 하지 못했다.)

 그래서 ② for 문(ie8 호환 방식)을 사용하게 되었다

 (위 코드는 그냥 for문을 사용해도 된다. 하지만 다른곳에서 문제가 발생하는 경우가 있었기에 적어둔다.)

 아무튼 다음 오픈 에디터와 같이 사용하는 경우에는 스크립트단에서의 for in 문의 사용은 자제하려 한다.

 



# 소스코드 - 임시 경로에 파일을 업로드 하고 업로드된 이미지를 받아오는 upload_class.php

<?php
// 업로드 폴더 경로
$uploadsDir = "./temporary";

// 업로드 가능한 확장자 지정
$allowedExt = array("jpg", "JPG", "jpeg", "JPEG", "png", "PNG", "gif", "GIF");

switch($_POST['mode']) {

    case "temporaryImageUpload" :

        $fileName = $_FILES['tmpFile']['name'];

        // 파일의 확장자를 분리
        $ext = array_pop(explode(".", $fileName));

        // 업로드 가능한 확장자 인지 확인한다.
        if(!in_array($ext, $allowedExt)) {
            $RetVal['message'] = "허용되지 않는 확장자입니다.";
        } else {

            // 업로드할 파일의 경로
            $tmpFile = $uploadsDir."/".date("YmdHis")."_".$fileName;

            if(move_uploaded_file($_FILES['tmpFile']['tmp_name'], $tmpFile)) {
                $RetVal['img'] = $tmpFile;
                $RetVal['ret'] = "succ";
            } else {
                $RetVal['message'] = "업로드시 문제가 발생하였습니다.\n다시 시도하여 주시기 바랍니다.";
            }
        }

        print json_encode($RetVal);
        return;
    break;

    default :
    break;
}
?>



# 출력결과






반응형
//

[jQuery] 이미지 슬라이드 제작[jQuery] 이미지 슬라이드 제작

Posted at 2018. 3. 10. 17:02 | Posted in JavaScript & jQuery/jQuery
반응형




■ 이미지 슬라이드 제작




# 소스코드 - main.php

<html>
<head>
<title>:: jQuery 슬라이드 ::</title>
</head>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<body style="text-align:center;">
    <!-- 캔버스 크기 800px -->
    <div id="canvas" style="position:absolute;top:5%;left:5%;width:800;">
        <?php include "./slider.php"; ?>
    </div>
</body>
</html>


※ 코드를 2개로 나누고 jQuery를 main.php에 선언한 이유

 실제로 개발시 만들어 두었던 slider.php 소스코드에도 jQuery를 선언해둔 채 그대로 가져다 두었다가

 언제부터인가 슬라이드 이동이 계속 가속을 하게 되더라.

 예제 쌤플에 굳이 그럴 필요는 없지만.

 원인을 찾기위해 뺑이쳤던게 억울하고 이런 실 수를 줄이기 위해 이 예제 포스트에서도 둘로 나누어 두었다.




# 소스코드 - slider.php

<style>
    * {
        margin:0px;
        padding:0px;
    }

    /* 애니메이션 캔버스 */
    .animation_canvas  {
        overflow:hidden;
        position:relative;
        float:left;
        width:100%;
    }
    
    .slide_section {
        position:absolute;
    }
    
    #leftMove {
        top:50%;
        left:2%;
    }

    #rightMove {
        top:50%;
        left:96%;
    }

    .slide_board {
        /* height:400px; */
    }

    .move_arrow {
        /* height:400px; */
        display:table-cell;
        vertical-align:middle;
    }

    /* 슬라이드 패널 */
    .slider_panel {
        width:calc(800px * 5);    /* 사용할 크기 x 갯수 */
        position:relative;
    }

    /* 슬라이드 이미지 */
    .slider_image {
        float:left;
        width:800px;
        /* height:400px; */
    }

    /* 슬라이드 텍스트 패널 */
    .slider_text_panel {
        position:absolute;
        top:10%;
        left:10%;
    }
    
    .slider_text {
        position:absolute;
        width:250px;
        height:150px;
    }

    .slider_text > h1 {
        background-color:#FFFFFF;
        opacity:0.5;
        margin:0px;
        padding:0px;
    }

    .slider_text > p {
        background-color:#C0C0C0;
        opacity:0.5;
        margin:0px;
        padding:0px;
    }

    /* 컨트롤 패널  */
    .control_panel  {
        position:absolute;
        overflow:hidden;
        top:90%;
        left:45%;
    }

    .control_button {
        font-size:11px;
        width:13px;
        height:13px;
        border:1px solid #D4D4D4;
        background-color:#F4F4F4;
        position:relative;
        float:left;
        cursor:pointer;
        margin-left:3px;
        margin-right:3px;
        text-align:center;
        font-weight:bold;
    }

    /* 컨트롤 마우스 오버  */
    .control_button:hover {
        border:1px solid #F4F4F4;
        background-color:#D4D4D4;
        color:#FFFFFF;
    }
    
    /* 컨트롤 현재 영역  */
    .control_button.active {
        border:1px solid #24822A;
        background-color:#24822A;
        color:#FFFFFF;
    }
</style>
<script>
jQuery(document).ready(function() {
    
    var canvasSize = jQuery("#canvas").css("width");
    var calcSize = canvasSize.split("px");
    jQuery(".slider_image").css("width", canvasSize);
    
    // 슬라이드의 전체 개수를 구한다.
    var slideMax = jQuery(".control_button").length;

    jQuery(".slider_panel").css("width", calcSize[0] * slideMax);

    // 슬라이드 이미지 좌우 이동버튼
    function moveArrow(sum) {

        var num = jQuery(".active").index();
        var index = jQuery(".active").index() + sum;

        if(index < 0) { index = slideMax; }
        if(index >= slideMax) { index = 0; }

        moveSlider(index);
    }

    // 슬라이드를 움직여주는 함수
    function moveSlider(index) {

        // 슬라이드를 이동합니다.
        var willMoveLeft = -(index * calcSize[0]);
        jQuery(".slider_panel").animate({ left: willMoveLeft }, "slow");

        // control_button에 active클래스를 부여/제거합니다.
        jQuery(".control_button[data-index=" + index + "]").addClass("active");
        jQuery(".control_button[data-index!=" + index + "]").removeClass("active");

        // 글자를 이동합니다.
        jQuery(".slider_text[data-index=" + index + "]").show().animate({
            left : 0
        }, "slow");
        jQuery(".slider_text[data-index!=" + index + "]").hide("slow", function() {
            jQuery(this).css("left", -300);
        });
    }

    // 초기 텍스트 위치 지정 및 data-index 할당
    jQuery(".slider_text").css("left", -300).each(function(index) {
        jQuery(this).attr("data-index", index);
    });

    // 좌우 슬라이드 넘김 버튼
    jQuery("#leftMove").on("click", function() { moveArrow(-1) });
    jQuery("#rightMove").on("click", function() { moveArrow(1) });

    // 컨트롤 버튼의 클릭 핸들러 지정 및 data-index 할당
    jQuery(".control_button").each(function (index) {
        jQuery(this).attr("data-index", index);
    }).click(function () {
        var index = jQuery(this).attr("data-index");
        moveSlider(index);
    });

    // 초기 슬라이드의 위치 지정
    var randomNumber = Math.floor(Math.random() * slideMax);
    moveSlider(randomNumber);

    var playAction = "";

    // 5초마다 한번씩 슬라이드를 자동으로 다음 페이지로 넘긴다.
    playAction = setInterval(function() {
        moveArrow(1);
    }, 5000);

    // 마우스가 슬라이드 위에 올라와 있는경우 / 빠져 나간 경우
    jQuery(".slide_board").hover(

        // 마우스가 슬라이드 위에 올라와 있는경우 그 움직임을 멈춘다.
        function() {
            clearInterval(playAction);
        }

        // 마우스가 슬라이드 위에 올라와있다 빠져 나간경우 자동 슬라이드를 초기화 하고 다시 시작한다.
        , function () {
            playAction = setInterval(function() {
                moveArrow(1);
            }, 5000);
        }
    );
});
</script>
<body style="text-align:center;">
    <div class="slide_board">
        <div class="animation_canvas">
            <div class="slider_panel">
                <img class="slider_image" src="./image/album_01.jpg">
                <img class="slider_image" src="./image/album_02.jpg">
                <img class="slider_image" src="./image/album_03.jpg">
                <img class="slider_image" src="./image/album_04.jpg">
                <img class="slider_image" src="./image/album_05.jpg">
            </div>
            <div class="slider_text_panel">
                <div class="slider_text">
                    <h1>TWICE</h1>
                    <p>JYP Entertainment</p>
                </div>
                <div class="slider_text">
                    <h1>Red Velvet</h1>
                    <p>SM Entertainment</p>
                </div>
                <div class="slider_text">
                    <h1>LOVELYZ</h1>
                    <p>Woollim Entertainment</p>
                </div>
                <div class="slider_text">
                    <h1>MOMOLAND</h1>
                    <p>Duble Kick Company</p>
                </div>
                <div class="slider_text">
                    <h1>GFRIEND</h1>
                    <p>Source Music Entertainment</p>
                </div>
            </div>
            <div class="control_panel">
                <div class="control_button">1</div>
                <div class="control_button">2</div>
                <div class="control_button">3</div>
                <div class="control_button">4</div>
                <div class="control_button">5</div>
            </div>
        </div>
        <div class="slide_section" id="leftMove">
            <div class="move_arrow">◀</div>
        </div>
        <div class="slide_section" id="rightMove">
            <div class="move_arrow">▶</div>
        </div>
    </div>
</body>




# 출력결과




# 첨부파일 : image_slider.zip




반응형
//