~~Title:jQuery 코드 조각~~
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, width=device-width, user-scalable=no, minimal-ui"> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="keywords" content=""> <meta name="description" content=""> <title>CSS Animate TEST</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="./lib/jquery-ui-1.12.1/jquery-ui.js"></script> <!-- 다운받아서 쓰자 --> </head> <!-- 문서 시작 ------------------------------- --> <body> <style> .samp_box { width: 100px; height: 100px; position: fixed; background: #0d77b6; } #sample_box_1 { left: 50px; top: 50px; } #sample_box_2 { left: 50px; top: 50px; display:none; } .btn_t1 { width: 100px; height: 30px; background-color:lightgray; position: relative; /* z-index 가 통하려면 position 이 필요하다 */ z-index: 100; border-style: solid; border-width: 1px; display:flex; /* 아래 키워드를 쓰기 위한 display:flex 추가 */ align-items: center; /* 세로 정렬, 센터 */ justify-content: center; /* 가로 정렬, 센터 */ } </style> <div id='sample_box_1' class='samp_box'></div> <div id='sample_box_2' class='samp_box'></div> <div id='btn_a' class='btn_t1'>클릭 A</div> <div id='btn_reset' class='btn_t1'>리셋</div> </body> <!-- 종료 ------------------------------- --> </html> <script> $('#btn_a').click(function () { //$(this).hide(); box_move(); }); $('#btn_reset').click(function () { box_reset(); }); // 박스 이동 function box_move() { var _box = $('#sample_box_1'); var _pos = _box.position(); var _doc_root = $(document); var _doc_w = _doc_root.width(); var _doc_h = _doc_root.height(); var _new_x = get_rand_int(0, _doc_w); var _new_y = get_rand_int(0, _doc_h); if (_pos.left == 50) { show_box_afterimage(); _box.animate( { left: _new_x + "px", top: _new_y + "px" }, 200, "easeOutBack", function() { setTimeout(function() { box_reset(); }, 500); }); } } // 박스 리셋 function box_reset() { var _box = $('#sample_box_1'); var _pos = _box.position(); show_box_afterimage(); _box.animate({ left: "50px", top: "50px" }, 200, "easeOutBack"); } function show_box_afterimage() { var _box1 = $('#sample_box_1'); var _box2 = $('#sample_box_2'); var _pos = _box1.position(); _box2.css({ opacity: 1, left: _pos.left, top: _pos.top }); _box2.show(); _box2.animate({ opacity: 0 }, 80, "linear"); } // https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/random function get_rand_int(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; //최댓값은 제외, 최솟값은 포함 } </script>