<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>길안내버튼</title>
<script>
// 길찾기 function
function RoadMapFind(portal,lng,lat,name)
{
if(portal==""){ alert("portal 값이 없습니다."); return false;}
if(lng==""){ alert("lng 값이 없습니다."); return false;}
if(lat==""){ alert("lat 값이 없습니다."); return false;}
if(name==""){ alert("name 값이 없습니다."); return false;}
var targetgul = "";
const user = navigator.userAgent;
if ( portal == "tmap" && !(user.indexOf("iPhone") > -1 || user.indexOf("Android") > -1 )) {
alert("T Map이 지원되지 않습니다.");
return;
}
switch(portal)
{
case "naver": targetgul = "http://map.naver.com/index.nhn?elng="+lng+"&elat="+lat+"&etext="+encodeURI(name)+"&menu=route&pathType=1"; break;
case "kakao": targetgul = "https://map.kakao.com/link/to/"+encodeURI(name)+","+lat+","+lng; break;
case "tmap": targetgul = "https://api2.sktelecom.com/tmap/app/routes?appKey=250d4611-11bb-4089-b0f7-12ce7c1e14a8&name="+encodeURI(name)+"&lon="+lng+"&lat="+lat; break;
}
var MapFindWindow = window.open(targetgul,"MapFindWindow");
MapFindWindow.focus();
}
// 창로드시
window.onload = function(){
// btn1 클릭시 처리
document.getElementById("btn1").onclick = function(){
RoadMapFind("naver",126.9783785,37.5666612,"서울시청");
}
// btn2 클릭시 처리
document.getElementById("btn2").onclick = function(){
RoadMapFind("kakao",126.9783785,37.5666612,"서울시청");
}
// btn3 클릭시 처리
document.getElementById("btn3").onclick = function(){
RoadMapFind("tmap",126.9783785,37.5666612,"서울시청");
}
}
</script>
</head>
<body>
<header>
<h1>길안내</h1>
</header>
<section>
<h2>길찾기</h2>
<nav>
<a id="btn1">네이버</a> |
<a id="btn2">카카오</a> |
<a id="btn3">티맵</a> |
<a onclick="RoadMapFind('naver',126.9783785,37.5666612,'서울시청')">네이버Click</a> |
<a onclick="RoadMapFind('kakao',126.9783785,37.5666612,'서울시청')">카카오Click</a> |
<a onclick="RoadMapFind('tmap',126.9783785,37.5666612,'서울시청')">티맵Click</a>
</nav>
<p>티맵은 어플로만 호출가능</p>
</section>
<footer></footer>
</body>
</html>
23. 9. 8.
길찾기 호출(위도,경도) Function (feat. 네이버,카카오,티맵)
23. 7. 19.
Javascript Text To Speak (TTS)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>TTS Sample</title>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no" />
<style>
#samplediv{ display:flex; flex-grow:1; width:100%;}
#speaktextarea{ flex-grow:1; height:200px; border:1px solid #000; font-size:24px; padding:6px;}
.btn{ display:flex; justify-content:center; align-items:center; background-color:#000; color:#fff; width:120px;}
</style>
<script>
function TextToSpeak(textstring)
{
// 지원확인
if(window.speechSynthesis)
{
const ssu = new SpeechSynthesisUtterance()
const synth = window.speechSynthesis
ssu.text = textstring;
synth.speak(ssu);
}
else
{
alert("지원안됨")
}
}
</script>
</head>
<body>
<div id="samplediv">
<textarea name="speaktextarea" id="speaktextarea"></textarea>
<a class="btn" onClick="TextToSpeak(document.getElementById('speaktextarea').value);">TTS</a>
</div>
</body>
</html>
22. 8. 4.
Jquery 한화면 단위 Mouse Wheel 이동 (응용)
JQuery 한화면 단위 Mouse Wheel 이동를 토대로 응용해서 복합적으로...
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Jquery MouseWheel 응용</title>
<style>
/*부드러운 스크롤 이동
html { scroll-behavior: smooth;}
*/
body{ margin:0; padding:0;}
header{ position:absolute; width:100%; height:100px; border-bottom:1px solid #000; display:flex; justify-content: center; align-items: center; float:left;}
section{ width:100%; height:100vh; display:flex; justify-content: center; align-items: center; float:left;}
footer{ width:100%; height:300px; border-top:1px solid #000; display:flex; justify-content: center; align-items: center; float:left;}
section:nth-child(odd){ background-color:#f1f1f1;}
.main1{ display:inline-block; height:1400px;}
.main4{ display:inline-block; height:800px;}
.main4 h2{ width:100%;}
#main4_sub{ width:100%; overflow:hidden; display:inline-block;}
#main4_sub[data-box='0'] .main4-box{ margin-left:0;}
#main4_sub[data-box='1'] .main4-box{ margin-left:-600px;}
#main4_sub[data-box='2'] .main4-box{ margin-left:-1200px;}
#main4_sub[data-box='3'] .main4-box{ margin-left:-1800px;}
#main4_sub[data-box='4'] .main4-box{ margin-left:-2400px;}
/*
#main4_sub[data-box='5'] .main4-box{ margin-left:-3000px;}
#main4_sub[data-box='6'] .main4-box{ margin-left:-3600px;}
*/
.main4-box{ display:flex; width:4200px; transition-duration:0.3s;}
.main4-box > div{ width:600px; display:flex; justify-content: center; align-items: center; height:600px; }
.main4-box > div:nth-child(odd){ background-color:#fff1f1;}
.main4-box > div:nth-child(even){ background-color:#f1fff1;}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
// 스크롤 중복입력 방지용 flag
var scrollworker = false;
// 스크롤 구간 배열
var scrollTops = [];
// 기본 이동시간 0.8초
var basicinterval = 800;
// 페이지 로드 후 동작
$(function(){
// scrollTops 구간목록을 배열로 구성
$("section").each(function(index, element) {
if($(this).offset().top!=undefined){
scrollTops.push($(this).offset().top)
}
});
// scrollTops 내임차순 정렬
scrollTops.sort(function(a, b) { return a - b;});
// 마지막 scrollTops 을 넘겨줄 위치를 구하기 위해
scrollTops.push(scrollTops[scrollTops.length -1] + window.outerHeight);
// header, section, footer 에서 마우스 휠을 넣었을 경우
$("header, section, footer").on("mousewheel", function (e) {
// 기존 이벤트 취소
e.preventDefault();
// 중복 입력 방지
if(scrollworker==false){
// 중복 입력 방지 on
scrollworker = true;
// 동작하고 있는 엘리먼트
const elm = $(this);
// 휠이벤트가 undefined 가 아니라면
if(event.wheelDelta!=undefined){
var delta = 0;
if (!event) event = window.event;
if (event.wheelDelta) {
delta = event.wheelDelta / 120;
if (window.opera) delta = -delta;
}
else if (event.detail)
delta = -event.detail / 3;
// 지금의 스크롤탑 위치
const nst = $(window).scrollTop();
// 어디로 움직일 것인가
var moveTop;
if($(elm).hasClass("main1")){ // main1 스크롤 이동 패스
// 연속 입력위해 scrollworker 지정
scrollworker = false;
if(delta < 0){ // 아래로
moveTop = "+=50";
}else if(delta>0){ // 휠위로
moveTop = "-=50";
}
// main1에선 기본 스크롤
$("html,body").stop().animate({
scrollTop: moveTop + 'px'
}, {
duration: 5,easing: "swing", complete: function () {
scrollworker = false;
}
});
return;
}else if($(elm).hasClass("main4")){ // main4 일 경우 조건 수행후 이어 동작시키기
// 조건을 수행시키기 위해 boxno 을 지정
var boxno = Number($("#main4_sub").attr("data-box"));
// 조건을 만족하는지에 대한 상태 flag
var movestat = false;
if(delta < 0){ // 아래로
boxno++;
// 조건값이 main4-box 의 수를 넘어가게 되면
if(boxno > $(".main4-box").length + 3){
boxno--;
// 지금의 scrollTop 위치보다큰 값중 첫번째 값 추출
moveTop = scrollTops.filter(x=> x > nst)[0];
// 값이 없으면 마지막값으로 지정
if(moveTop == undefined) moveTop = scrollTops[scrollTops.length-1];
// 조건상태 만족처리
movestat = true;
}
}else if(delta>0){ // 휠위로
boxno--;
// 조건값이 최소라면
if(boxno < 0){
// 지금의 scrollTop 위치보다 작은 값 추출
var nstminArr = scrollTops.filter(x => x < nst);
// 역순정렬
nstminArr.sort(function(a, b) { return b - a;});
// 역순정렬한 첫번째값 추출
moveTop = nstminArr[0];
// 첫번째값이 undefined 면 움직일 위치 0으로 지정
if(moveTop == undefined) moveTop = 0;
movestat = true;
}
}
// 변경된 조건으로 스타일 적용
$("#main4_sub").attr("data-box",boxno);
// 조건에 따라 scrollTop을 지정하기 위해 변수지정
var intervals = basicinterval;
// 조건에 만족하지 않으면 움직임이 없도록 고정시킴
if(!movestat) { intervals=0; moveTop=$(".main4").offset().top;}
// scrollTop 이동
$("html,body").stop().animate({
scrollTop: moveTop + 'px'
}, {
duration: intervals,easing: "swing", complete: function () {
scrollworker = false;
}
});
}else{ // 그외일경우 일반적 진행
if(delta < 0){ // 아래로
// 지금의 scrollTop 위치보다큰 값중 첫번째 값 추출
moveTop = scrollTops.filter(x=> x > nst)[0];
// 값이 없으면 마지막값으로 지정
if(moveTop == undefined) moveTop = scrollTops[scrollTops.length-1];
}else if(delta>0){ // 휠위로
// 지금의 scrollTop 위치보다 작은 값 추출
var nstminArr = scrollTops.filter(x => x < nst);
// 역순정렬
nstminArr.sort(function(a, b) { return b - a;});
// 역순정렬한 첫번째값 추출
moveTop = nstminArr[0];
// 첫번째값이 undefined 면 움직일 위치 0으로 지정
if(moveTop == undefined) moveTop = 0;
}
// scrollTop 이동
$("html,body").stop().animate({
scrollTop: moveTop + 'px'
}, {
duration: basicinterval,easing: "swing", complete: function () {
scrollworker = false;
}
});
}
}
}
});
});
$(window).resize(function(){
scrollTops = [];
$("section").each(function(index, element) {
if($(this).offset().top!=undefined){
scrollTops.push($(this).offset().top)
}
});
scrollTops.sort(function(a, b) { return a - b;});
scrollTops.push(scrollTops[scrollTops.length -1] + window.outerHeight);
});
</script>
</head>
<body>
<header>
<h1>Header</h1>
</header>
<section class="main0">
<h2>Main 0</h2>
</section>
<section class="main1">
<h2>Main 1</h2>
</section>
<section class="main2">
<h2>Main 2</h2>
</section>
<section class="main3">
<h2>Main 3</h2>
</section>
<section class="main4">
<div>
<h2>Main 4</h2>
<div id="main4_sub" data-box="0">
<div class="main4-box">
<div class="main4-box-1">4-1</div>
<div class="main4-box-2">4-2</div>
<div class="main4-box-3">4-3</div>
<div class="main4-box-4">4-4</div>
<div class="main4-box-5">4-5</div>
<div class="main4-box-6">4-6</div>
<div class="main4-box-7">4-7</div>
</div>
</div>
</div>
</section>
<footer>
<h1>Footer</h1>
</footer>
</body>
</html>
라벨:
웹,
HTML,
Javascript,
JQuery
22. 1. 19.
Javascript 동적 드래그 앤 드롭 레이어 생성
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>드래그 앤 드롭 동적 생성</title>
<style>
html, body {margin:0; padding:0; }
#content { position:relative; width:100%; height:70vh; background-color:#f1f1f1; display:inline-block; overflow:scroll; }
.formdiv { width: 300px; height: 300px; display: inline-block; border: 1px solid #000; background-color: #000; position: absolute; cursor:move; left:0; top:0; }
</style>
<script>
// 시작위치
var startX = 0;
var startY = 0;
// 클릭위치
var clickX = 0;
var clickY = 0;
// 맨앞으로
var zIndex = 0;
function DragStartFunction(ev,el) {
if (el.style.left != undefined) {
startX = el.style.left;
startX = Number(startX.replace("px", ""));
}
if (el.style.top != undefined) {
startY = el.style.top;
startY = Number(startY.replace("px", ""));
}
clickX = ev.clientX - startX;
clickY = ev.clientY - startY;
}
function DragEndFunction(ev) {
var moveX = ev.clientX - clickX;
var moveY = ev.clientY - clickY;
ev.target.style.left = moveX + "px";
ev.target.style.top = moveY + "px";
zIndex++;
ev.target.style.zIndex = zIndex;
}
window.onload = function () {
document.getElementById("btn").onclick = function () {
var newDiv = document.createElement("div");
newDiv.className = "formdiv";
newDiv.setAttribute("draggable", true);
newDiv.setAttribute("ondragstart", "DragStartFunction(event,this)");
newDiv.setAttribute("ondragend", "DragEndFunction(event)");
// 구분을 위해 랜덤색상
newDiv.setAttribute("style", "background-color:#" + Math.round(Math.random() * 0xffffff).toString(16));
document.getElementById("content").appendChild(newDiv);
}
}
</script>
</head>
<body>
<a id="btn">ADD</a>
<div id="content"></div>
</body>
</html>
라벨:
웹,
HTML,
Javascript
22. 1. 13.
웹페이지 페이지 이동(?) 갱신( Javascript History Api )
페이지 이동시 부드럽게 이동하기 위한 방법(=한페이지에서 변화를...)
Javascript 파일(/main.js)
PHP 페이지(/index.php, /A/index.php) : 복붙을 위해...
페이지구성(/header.html)
PHP 구성(/main.php)
PHP 구성(/A/main.php)
Javascript 파일(/main.js)
// 뒤로가기시 페이지 새로고침
window.onpopstate = function(event) {
var np = document.location
BodyClassLoad(np);
}
// 페이지 시작시 a태그의 href 조정(타 도메인일경우 그대로 두고 같은 도메인일 경우 function 으로 처리되도록..)
window.onload = function(){
var abtn = document.querySelectorAll("a");
for(var i = 0; i < abtn.length; i++){
const loc = abtn[i].getAttribute("href");
if(loc.indexOf("://") == -1){
MoveHrefClick(abtn[i],loc);
}else{
if(loc.indexOf("://"+window.location.origin) > -1){
MoveHrefClick(abtn[i],loc);
}
}
}
}
// body class 조정 및 section 의 내용 교체
function BodyClassLoad(url){
var nc = "";
var mhref = "";
if(url.origin != undefined){
nc = url.href.substring(url.origin.length,url.origin.length+url.href.length);
}else{
nc = url;
}
mhref = nc;
if(nc.substring(0,1)=="/"){
nc = nc.substring(1,nc.length);
}
if(nc.substring(nc.length-1,nc.length)=="/"){
nc = nc.substring(0,nc.length - 1);
}
nc = nc.replace("/"," ");
document.querySelector("body").className = "BodyTag "+ nc;
var xhr = new XMLHttpRequest();
var loadurl = mhref;
if(loadurl.indexOf("?") == -1){
loadurl += "/main.php";
loadurl = loadurl .replace("//","/");
}else{
// PHP 페이지를 불러오도록 상황에 따라 변경
loadurl = loadurl .replace("?","main.php?");
}
xhr.open('GET', loadurl, true);
xhr.send();
xhr.onload = function(){
if (xhr.status == 200) {
document.querySelector("section").innerHTML = xhr.response;
} else {
// 실패
}
}
}
// a태그 href 비활성화 및 history 에 이전주소로 기록
function MoveHrefClick(el,href){
el.removeAttribute("href");
el.onclick = function(){
history.pushState({page: 1}, document.title, href);
BodyClassLoad(href)
}
}
PHP 페이지(/index.php, /A/index.php) : 복붙을 위해...
<?php
$relative_path = preg_replace("`\/[^/]*\.php$`i", "/", $_SERVER['PHP_SELF']);
$pathNode = explode( '/', $relative_path );
$bodyClass = "BodyTag";
for( $i = 0;$i < sizeof($pathNode); $i++){
if($pathNode[$i] != ""){
$bodyClass .= " ".$pathNode[$i];
}
}
$path1 = "Order";
$path2 = "";
$path3 = "";
if($bodyClass != "BodyTag"){
if(sizeof($pathNode)>1){
$path1 = $pathNode[1];
}
if(sizeof($pathNode)>2){
$path2 = $pathNode[2];
}
if(sizeof($pathNode)>3){
$path3 = $pathNode[3];
}
}else{
$bodyClass .= " ".$path1;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="/main.js" defer></script>
</head>
<body class="<?php echo $bodyClass; ?>">
<header><?php include $_SERVER["DOCUMENT_ROOT"]."/header.html"; ?></header>
<section><?php include $_SERVER["DOCUMENT_ROOT"].$relative_path."main.php"; ?></section>
<footer><?php include $_SERVER["DOCUMENT_ROOT"]."/footer.html"; ?></footer>
</body>
</html>
페이지구성(/header.html)
<a href="/">Home</a> <a href="/A/">A</a>
PHP 구성(/main.php)
<h2>Home</h2>
PHP 구성(/A/main.php)
<h2>A</h2>
라벨:
웹,
HTML,
Javascript,
PHP
21. 7. 26.
제이쿼리(Jquery) 탭메뉴(Tab Menu)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Tab 메뉴</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(function () {
$(".tabbtn").on("click", function () {
var index = $(this).index();
$(this).addClass("active").siblings().removeClass("active");
$(".tablist").removeClass("active").eq(index).addClass("active");
});
});
</script>
<style>
.tabnav{ width:100%; display:inline-block; float:left;}
.tabnav > .tabbtn{ display:inline-block; float:left; margin-left:-1px; border-radius:0.5em 0.5em 0 0; border:1px solid #ddd; padding:0.5em 1em; cursor:pointer;}
.tabnav > .active{ font-weight:900; background-color:#0094ff; color:#fff; cursor:auto;}
.tab{ margin:0; margin-top:-1px; padding:0; width:100%; display:inline-block; float:left;}
.tab > .tablist{ display:none; list-style:none; margin:0; padding:0; border:1px solid #ddd;}
.tab > .active{ padding:0.5em; display:block; min-height:300px;}
</style>
</head>
<body>
<nav class="tabnav">
<a class="tabbtn active">Tab1</a>
<a class="tabbtn">Tab2</a>
<a class="tabbtn">Tab3</a>
</nav>
<ul class="tab">
<li class="tablist active">
Tab1 Content
</li>
<li class="tablist">
Tab2 Content
</li>
<li class="tablist">
Tab3 Content
</li>
</ul>
</body>
</html>
Javascript 버전
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Tab 메뉴</title>
<script>
window.onload = function () {
var btns = document.querySelectorAll(".tabbtn");
for (var i = 0; i < btns.length; i++) {
btns[i].setAttribute("onclick", "btnClick(" + i + ");");
}
}
function btnClick(index) {
var tabbtn = document.getElementsByClassName("tabbtn");
var tablist = document.getElementsByClassName("tablist");
for (var i = 0; i < tabbtn.length; i++) {
if (index == i) {
tabbtn[i].className = "tabbtn active";
tablist[i].className = "tablist active";
} else {
tabbtn[i].className = "tabbtn";
tablist[i].className = "tablist";
}
}
}
</script>
<style>
.tabnav{ width:100%; display:inline-block; float:left;}
.tabnav > .tabbtn{ display:inline-block; float:left; margin-left:-1px; border-radius:0.5em 0.5em 0 0; border:1px solid #ddd; padding:0.5em 1em; cursor:pointer;}
.tabnav > .active{ font-weight:900; background-color:#0094ff; color:#fff; cursor:auto;}
.tab{ margin:0; margin-top:-1px; padding:0; width:100%; display:inline-block; float:left;}
.tab > .tablist{ display:none; list-style:none; margin:0; padding:0; border:1px solid #ddd;}
.tab > .active{ padding:0.5em; display:block; min-height:300px;}
</style>
</head>
<body>
<nav class="tabnav">
<a class="tabbtn active">Tab1</a>
<a class="tabbtn">Tab2</a>
<a class="tabbtn">Tab3</a>
</nav>
<ul class="tab">
<li class="tablist active">
Tab1 Content
</li>
<li class="tablist">
Tab2 Content
</li>
<li class="tablist">
Tab3 Content
</li>
</ul>
</body>
</html>
라벨:
웹,
HTML,
Javascript,
JQuery
21. 5. 4.
Javascript 사다리 게임( ladder Game)
그냥 만들어봤던 SVG로 만든 js 사다리 게임
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>사다리게임</title>
<style>
html,body{padding:0; margin:0; }
ul,li{ padding:0; margin:0; list-style:none;}
#div1{ display:inline-block; position:relative;}
#div1 > ul{ display:inline-block; position:relative; width:100%;}
#div1 > ul > li{ display:inline-block; float:left; text-align:center;}
#div1 > ul > li > input{ width:90%; text-align:center; }
#ladderboder{ position:relative; float:left;}
#ladderbody{ position:relative; display:inline-block;}
#ladderresult{ position:absolute; left:0; top:0;}
input{ border:1px solid;}
</style>
<script>
// 인원제한
var maxuser = 20;
var linewidth = 80;
var svgHeight = 500;
var gridline = [];
var resultline = [];
var resultobj = { "user": 0, "list": [], "line": [] };
var linecolor = [];
window.onload = function () {
var btn1 = document.getElementById("btn1");
btn1.addEventListener("click", function () {
linecolor = [];
gridline = [];
resultline = [];
resultobj = { "user": 0, "list": [], "line": [] };
var num = document.getElementById("num").value;
if (num == undefined || num == "" || !Number(num)) {
num = 0;
}
if (num <= 1) {
alert("참여인원을 입력하세요.(최소 2명입니다.)");
document.getElementById("num").value = "";
document.getElementById("num").focus();
return;
}
if (num > maxuser) {
alert("참여인원은 최대 " + maxuser + "명입니다");
document.getElementById("num").value = "";
document.getElementById("num").focus();
return;
}
resultobj.user = num;
var html = [];
for (var i = 0; i < num; i++) {
// 랜덤컬러
var rndcolor = "#" + Math.round(Math.random() * 0xffffff).toString(16);
linecolor.push(rndcolor);
html.push("<li><input type=\"text\" style=\"border:1px solid " + rndcolor + "\" name=\"lname\" placeholder=\"이름" + (i + 1) + "\" onmouseover=\"LineResult(" + i + ")\" onmouseout=\"LineResultView()\"/></li>");
}
document.getElementById("ladderheader").innerHTML = html.join('');
var html = [];
for (var i = 0; i < num; i++) {
html.push("<li><input type=\"text\" name=\"litem\" placeholder=\"상품" + (i + 1) + "\"/></li>");
}
document.getElementById("ladderfooter").innerHTML = html.join('');
document.getElementById("resultuser").innerHTML = "";
var svgw = (num * linewidth);
document.getElementById("ladderboder").style.width = (num * linewidth) + "px";
document.getElementById("ladderboder").style.height = svgHeight + "px";
document.getElementById("ladderresult").style.width = (num * linewidth) + "px";
document.getElementById("ladderresult").style.height = svgHeight + "px";
document.getElementById("ladderresult").style.display = "none";
var svg = [];
svg.push("<svg onclick=\"XYSetting(event);\" id=\"laddersvg\" width=\"" + svgw + "\" height=\"" + svgHeight + "\">");
for (var i = 0; i < num; i++) {
var x = ((linewidth / 2) + (i * linewidth));
svg.push("<line x1=\"" + x + "\" y1=\"0\" x2=\"" + x + "\" y2=\"" + svgHeight + "\" stroke=\"#000\" stroke-width=\"1\"/>");
}
svg.push("</svg>");
var lb = document.getElementById("ladderboder");
lb.innerHTML = svg.join('');
var l = document.querySelectorAll("#div1 > ul > li");
l.forEach(function (el) {
el.style.width = linewidth + "px";
})
});
var btn2 = document.getElementById("btn2");
btn2.addEventListener("click", function () {
var ladderresult = document.getElementById("ladderresult");
ladderresult.style.display = "inline-block";
var rline = [];
for (var i = 0; i < gridline.length; i++) {
var ix = (gridline[i].x - 40) / linewidth;
rline.push({ "x1": gridline[i].x, "x2": gridline[i].x + linewidth, "y": gridline[i].y });
rline.push({ "x1": gridline[i].x + linewidth, "x2": gridline[i].x, "y": gridline[i].y });
}
for (var i = 0; i < resultobj.user; i++) {
var x = ((linewidth / 2) + (i * linewidth));
// rline.push({ "x1": x, "x2": x, "y": 0 });
rline.push({ "x1": x, "x2": x, "y": svgHeight });
}
rline.sort(function (a, b) {
return a["y"] - b["y"];
});
var svg = [];
svg.push("<svg id=\"ladderresultsvg\" width=\"100%\" height=\"100%\">");
for (var i = 0; i < resultobj.user; i++) {
var lcolor = linecolor[i % linecolor.length];
var resultusr = document.getElementsByName("lname")[i].value;
if (resultusr == "") {
resultusr = document.getElementsByName("lname")[i].getAttribute("placeholder");
}
console.log(lcolor);
var linelist = [];
var bx = (i * linewidth) + (linewidth / 2);
var by = 0;
linelist.push({ "x": bx, "y": by });
for (var j = 0; j < rline.length; j++) {
if (rline[j].x1 == bx && by > rline[j].y - 1) {
linelist.push({ "x": bx, "y": by });
linelist.push({ "x": rline[j].x2, "y": rline[j].y });
svg.push("<line x1=\"" + bx + "\" y1=\"" + rline[j].y + "\" x2=\"" + rline[j].x2 + "\" y2=\"" + rline[j].y + "\" stroke=\"" + lcolor + "\" stroke-width=\"1\" data-line=\"" + i + "\"/>");
bx = rline[j].x2;
} else if (rline[j].x2 == bx && by > rline[j].y - 1) {
linelist.push({ "x": bx, "y": by });
linelist.push({ "x": rline[j].x1, "y": rline[j].y });
svg.push("<line x1=\"" + rline[j].x1 + "\" y1=\"" + rline[j].y + "\" x2=\"" + bx + "\" y2=\"" + rline[j].y + "\" stroke=\"" + lcolor + "\" stroke-width=\"1\" data-line=\"" + i + "\"/>");
bx = rline[j].x1;
}
by = rline[j].y;
}
linelist.push({ "x": bx, "y": svgHeight });
var ix = (bx - 40) / linewidth;
document.getElementsByName("litem")[ix].style.borderColor = linecolor[i];
document.getElementsByName("litem")[ix].setAttribute("onmouseover", "LineResult(" + i + ");");
document.getElementsByName("litem")[ix].setAttribute("onmouseout", "LineResultView();");
var itemresult = document.getElementsByName("litem")[ix].value;
if (itemresult == "") {
itemresult = document.getElementsByName("litem")[ix].getAttribute("placeholder");
}
var html = [];
html.push("<p style=\"color:" + linecolor[i] + "\">" + resultusr + " → " + itemresult + "</p>");
resultuser.innerHTML += html.join('');
var bx = 0;
var by = 0;
for (var j = 0; j < linelist.length; j++) {
if (j % 2 == 0) {
svg.push("<line x1=\"" + linelist[j].x + "\" y1=\"" + linelist[j].y + "\" ");
bx = linelist[j].x;
by = linelist[j].y;
} else {
svg.push(" x2=\"" + linelist[j].x + "\" y2=\"" + linelist[j].y + "\" stroke=\"" + lcolor + "\" stroke-width=\"1\" data-line=\"" + i + "\"/>");
}
}
}
svg.push("</svg>");
ladderresult.innerHTML = svg.join('');
});
}
function XYSetting(e) {
var lb = document.getElementById("ladderboder");
var svgtop = lb.getBoundingClientRect().top;
var x = Math.floor((e.pageX + (linewidth / 2)) / linewidth) * linewidth - (linewidth / 2);
var y = e.pageY - svgtop;
if (x > 0 && x < document.getElementById("laddersvg").clientWidth - (linewidth / 2)) {
var check = false;
var cli = 0;
for (var i = 0; i < gridline.length; i++) {
if (Number(gridline[i].x) == Number(x) && Number(gridline[i].y) == Number(y)) {
check = true;
cli = i;
}
}
if (check) {
gridline.splice(cli, 1);
} else {
var chk = false;
for (var i = 0; i < gridline.length; i++) {
if (gridline[i].y == y) {
chk = true;
}
}
if (!chk) {
gridline.push({ "x": x, "y": y });
}
}
var addsvg = [];
addsvg.push("<svg onclick=\"XYSetting(event);\" id=\"laddersvg\" width=\"" + lb.clientWidth + "\" height=\"" + svgHeight + "\">");
var num = (lb.clientWidth / linewidth);
// 기본라인
for (var i = 0; i < num; i++) {
var x = ((linewidth / 2) + (i * linewidth));
addsvg.push("<line x1=\"" + x + "\" y1=\"0\" x2=\"" + x + "\" y2=\"" + svgHeight + "\" stroke=\"#000\" stroke-width=\"1\"/>")
}
for (var i = 0; i < gridline.length; i++) {
var sx = (gridline[i].x);
var sy = gridline[i].y;
addsvg.push("<line x1=\"" + sx + "\" y1=\"" + sy + "\" x2=\"" + (sx + linewidth) + "\" y2=\"" + sy + "\" stroke=\"#000\" stroke-width=\"1\"/>")
}
addsvg.push("</svg>");
var lbs = document.getElementById("ladderboder");
lbs.innerHTML = addsvg.join('');
}
}
function LineResult(no) {
if (document.getElementById("ladderresultsvg") != undefined)
document.getElementById("ladderboder").style.opacity = 0;
var elm = document.querySelectorAll("#ladderresultsvg line");
for (var i = 0; i < elm.length; i++) {
if (elm[i].getAttribute("data-line") == no) {
elm[i].style.opacity = 1;
} else {
elm[i].style.opacity = 0;
}
}
}
function LineResultView() {
if (document.getElementById("ladderresultsvg") != undefined)
document.getElementById("ladderboder").style.opacity = 1;
var elm = document.querySelectorAll("#ladderresultsvg line");
for (var i = 0; i < elm.length; i++) {
elm[i].style.opacity = 1;
}
}
</script>
</head>
<body>
<form>
<input type="number" id="num" placeholder="참여인원" />
<a id="btn1">참여인원</a>
<a id="btn2">결과확인</a>
</form>
<div id="div1">
<ul id="ladderheader"></ul>
<div id="ladderbody">
<div id="ladderboder"></div>
<div id="ladderresult"></div>
</div>
<ul id="ladderfooter"></ul>
<div id="resultuser"></div>
</div>
</body>
</html>
라벨:
HTML,
Javascript,
SVG
20. 9. 9.
Jquery Layer Popup(Drag & Drop)
은근히 쓰게되는 제이쿼리 레이어팝업...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<title>레이어 팝업</title>
<style>
/* Layer 팝업 css */
.LayerPopupTbl {position: absolute;border: 1px solid #2d2d2d;display: table;background-color: #ffffff;border-collapse: collapse;}
.LayerPopupTbl > thead > tr > td {width: 100%;padding-top: 3px;padding-bottom: 3px;background-color: #00CCFF;text-align: right;}
.LayerPopupTbl > tbody > tr > td {background-color: #FFF;display: table-cell;}
.LayerPopupTbl > tbody > tr > td img {margin:-1px;float:left;}
.LayerPopupTbl > tfoot > tr > td {background-color: #c9c9c9;padding: 3px;}
</style>
<script>
/* Popup */
var PopupmoveX = 0;
var PopupmoveY = 0;
var topPopup = 0;
var leftPopup = 0;
function zIndexReload(ele) {
$(ele).css("z-index", 1000).siblings().css("z-index", 999);
}
function Popupdrag(ev) {
if ($(ev.target).offset() != undefined) {
topPopup = ev.clientY - $(ev.target).offset().top;
leftPopup = ev.clientX - $(ev.target).offset().left;
}
PopupmoveX = ev.clientX;
PopupmoveY = ev.clientY;
}
function Popupdrop(ev) {
PopupmoveX = ev.clientX;
PopupmoveY = ev.clientY;
$(ev.target).css("top", (PopupmoveY - topPopup)).css("left", (PopupmoveX - leftPopup));
}
function setCookie(name, value, expiredays) {
var todayDate = new Date();
todayDate.setDate(todayDate.getDate() + expiredays);
//todayDate.getDate()- localtime의 달의 날짜를 반환(1~31). setDate의경우 달의 날짜를 설정
document.cookie = name + '=' + escape(value) + '; path=/; expires=' + todayDate.toGMTString() + ';';
}
function getCookie(name) {
var nameOfCookie = name + '=';
var x = 0;
while (x <= document.cookie.length) {
var y = (x + nameOfCookie.length);
if (document.cookie.substring(x, y) == nameOfCookie) {
if ((endOfCookie = document.cookie.indexOf(';', y)) == -1)
endOfCookie = document.cookie.length;
return unescape(document.cookie.substring(y, endOfCookie));
}
x = document.cookie.indexOf(' ', x) + 1;
if (x == 0)
break;
}
return '';
}
// 오늘 하루 이창을 열지 않음
function PopupClose(elem) {
var elemName = $(elem).parents("table:first").attr("id");
setCookie(elemName, 'done', 1); // 오른쪽 숫자는 쿠키를 유지할 기간을 설정합니다
$(elem).parents("table:first").remove();
}
$(function () {
/* 목록만큼 돌린다 */
for (var i in popupArray) {
var mypopupName = popupArray[i].name;
var mypopupTop = popupArray[i].top;
var mypopupLeft = popupArray[i].left;
var mypopuphtml = popupArray[i].html;
/* 오늘 하루 이창 열지 않음을 누른상태가 아니라면 보여준다. */
if (getCookie(mypopupName) != "done") {
var popuptbl = document.createElement("table");
popuptbl.setAttribute("class", "LayerPopupTbl");
popuptbl.setAttribute("id", mypopupName);
popuptbl.setAttribute("draggable", true);
popuptbl.setAttribute("ondragstart", "Popupdrag(event)");
popuptbl.setAttribute("ondragend", "Popupdrop(event)");
popuptbl.setAttribute("onmouseover", "zIndexReload(this)");
popuptbl.style.top = mypopupTop;
popuptbl.style.left = mypopupLeft;
var formhtml = [];
formhtml.push("<thead><tr><td><a onclick=\"$(this).parents('table:first').remove();\">[닫기]</a></td></tr></thead>");
formhtml.push("<tbody><tr><td>" + mypopuphtml + "</td></tr></tbody>");
formhtml.push("<tfoot><tr><td><label><input type=\"checkbox\" onClick=\"PopupClose(this);\" /> 오늘 하루 이창을 열지 않음</label></td></tr></tfoot>");
popuptbl.innerHTML = formhtml.join("");
document.body.appendChild(popuptbl);
}
}
});
/* 팝업목록 name=팝업이름(id), top:팝업위치, left: 팝업위치, html : 팝업내용 - 만질경우 이부분만 고쳐서 사용하려고 구성... */
var popupArray = [
/* 팝업1 */
{ "name": "POPUP_ex_1", "top": "8px", "left": "20px", "html": "<a href='http://www.naver.com'><img alt='' src='https://ssl.pstatic.net/static/kin/09renewal/banner_roulette.png'/></a>" },
/* 팝업2 */
{ "name": "POPUP_ex_2", "top": "8px", "left": "300px", "html": "<div style=\"background-color:yellow\"><h4 style=\"margin:0;padding:0;line-height:1.6;\">공지사항</h4><p style=\"margin:0;padding:0;line-height:1.6;\">안녕하세요</p></div>" },
/* 팝업3 */
{ "name": "POPUP_ex_3", "top": "176px", "left": "20px", "html": "<img alt='' src='https://ssl.pstatic.net/static/kin/09renewal/bingo_banner.png'>" },
]
</script>
</head>
<body>
</body>
</html>
라벨:
웹,
HTML,
Javascript,
JQuery
20. 8. 10.
Javascript 링크이동없이 URL 바꾸기
참고 : https://developer.mozilla.org/ko/docs/Web/API/History/pushState
p.html
page.html
p.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style>
a {
background-color: #000;
color: #fff;
margin: 2px;
cursor: pointer;
}
</style>
<script>
window.onload = function () {
document.getElementById("btn1").addEventListener("click", function () {
var page = 1;
var state = { 'page_id': page, 'user_id': "" }
var title = ''
var url = 'page.html?page=' + page;
history.pushState(state, title, url);
// Javascript
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('XMLHTTP Fail');
return false;
}
httpRequest.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
document.getElementById("view").innerHTML = this.responseText;
} else {
alert('Error');
}
}
};
httpRequest.open('GET', url);
httpRequest.send();
});
document.getElementById("btn2").addEventListener("click", function () {
var page = 2;
var state = { 'page_id': page, 'user_id': "" }
var title = ''
var url = 'page.html?page=' + page;
history.pushState(state, title, url);
// JQuery
$.ajax({
type: "GET",
url: url,
success: function (res) {
$("#view").html(res);
}
});
});
}
</script>
</head>
<body>
<a id="btn1">Page 1</a>
<a id="btn2">Page 2</a>
<div id="view"></div>
</body>
</html>
page.html
Page 입니다
라벨:
웹,
Ajax,
HTML,
Javascript,
JQuery
20. 6. 9.
Javascript & JQuery Rainbow Text Effect
Rainbow Text Animation
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<title>JQuery Rainbow Animation</title>
<style>
.RainbowText{ text-align:center;}
.RainbowText > span{ font-size:30px; font-weight:900; animation-duration:1s; animation-iteration-count:infinite;}
</style>
<script>
// 색상목록
var rainbowArr = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];
// 클래스명
var className = "RainbowText";
$(function () {
var html = [];
html.push("<style>");
// rainbowArr에 넣은 수만큼 클래스를 만든다.
for (var i = 0; i < rainbowArr.length; i++) {
// 클래스 선언
html.push(".rainbow" + i + "{color:" + rainbowArr[i] + ";animation-name:rainbow" + i + "Ani;}");
// 애니메이션 키프레임 선언
html.push("@keyframes rainbow" + i + "Ani{");
for (var j = i; j < i + rainbowArr.length + 1; j++) {
// 0% ~ 100% 가 등록한 배열순서대로 색상이 되도록 처리
html.push(((100 / rainbowArr.length) * (j - i)) + "%{color:" + rainbowArr[((j) % rainbowArr.length)] + "}");
}
html.push("}");
}
html.push("</style>");
// body 에 추가
$("body").append(html.join("\n"))
// 선언한 클래스에 html 을 치환
$("." + className).each(function () {
var str = $(this).text();
var html = [];
// text 수 만큼
for (var i = 0; i < str.length; i++) {
// span 으로 잘개쪼개고 클래스명을 지정
html.push("<span class=\"rainbow" + (i % rainbowArr.length) + "\">" + str.substring(i, i + 1) + "</span>");
}
// 클래스의 html태그를 변경
$(this).html(html.join(""));
});
});
</script>
</head>
<body>
<div class="RainbowText">Rainbow</div>
<div class="RainbowText">■■■■■■■</div>
</body>
</html>
라벨:
웹,
HTML,
Javascript,
JQuery
19. 12. 13.
Javascript & JQuery 퀵 메뉴
간단하게 만들어본 제이쿼리 퀵메뉴
자바스크립트(Javascript)로 변경해 봄
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<style>
.quick { position:absolute; width: 150px; top:0; right:0; display: inline-block; transition-duration: 1s; margin-top:10em; margin-right:1em; }
/* 스크롤바 박스 */
.quick > div { background-color: #f1f1f1; border: 2px solid #ddd; border-radius: 0.5em;}
</style>
<script>
// 스크롤을 만들기위해 body 를 키움 없애도 뎀
$(function () { $("html,body").css("height", "10000px");});
// 따라다니게 하기 위한 처리
$(window).scroll(function (e) {
$(".quick").css("top", $(this).scrollTop()+"px");
});
</script>
</head>
<body>
<div class="quick">
<div>
<ul>
<li><a>menu 1</a></li>
<li><a>menu 2</a></li>
<li><a>menu 3</a></li>
<li><a>menu 4</a></li>
<li><a>menu 5</a></li>
</ul>
</div>
</div>
</body>
</html>
자바스크립트(Javascript)로 변경해 봄
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
.quick { position:absolute; width: 150px; top:0; right:0; display: inline-block; transition-duration: 1s; margin-top:10em; margin-right:1em; }
/* 스크롤바 박스 */
.quick > div { background-color: #f1f1f1; border: 2px solid #ddd; border-radius: 0.5em;}
</style>
<script>
// 창크기 키워 스크롤 나오게 하기
window.onload = function () {
document.getElementsByTagName("body")[0].style.height = "10000px";
}
window.addEventListener('scroll', function (e) {
document.querySelector(".quick").style.top = window.scrollY + "px"
})
</script>
</head>
<body>
<div class="quick">
<div>
<ul>
<li><a>menu 1</a></li>
<li><a>menu 2</a></li>
<li><a>menu 3</a></li>
<li><a>menu 4</a></li>
<li><a>menu 5</a></li>
</ul>
</div>
</div>
</body>
</html>
라벨:
웹,
HTML,
Javascript,
JQuery
19. 4. 24.
Javascript 한화면 단위 Mouse Wheel 이동
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>MouseWheel</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<style type="text/css">
html,body{ margin:0; padding:0; width:100%; height:100%;}
.box{ width:100%; height:100%; position:relative; color:#ffffff; font-size:24pt;}
</style>
<script type="text/javascript">
// 적용할 클래스명
var className = "box";
// 지금의 스크롤 위치를 담을 변수
var currentScroll = 0;
// 에니메이션 효과를 주기위한 function 명 선언
var tim;
window.onload = function () {
/* Div Class 명 */
// box클래스 추출
var elm = document.getElementsByClassName(className);
// box클래스 개수만큼 실행
for (var i = 0; i < elm.length; i++) {
// box 에 각각 마우스 휠 감지
// 휠감지
elm[i].addEventListener("mousewheel", MouseWheelHandler, false);
// firefox 용 휠처리
elm[i].addEventListener("DOMMouseScroll", MouseWheelHandler, true);
}
}
function MouseWheelHandler(e) {
// 스크롤 취소시킴(이걸 안할경우 도중에 명령을 받아 화면이 덜덜 거릴수 있음)
e.preventDefault();
// 휠값처리
var delta = 0;
if (!event) event = window.event;
if (event.wheelDelta) {
delta = event.wheelDelta / 120;
if (window.opera) delta = -delta;
}
else if (event.detail)
delta = -event.detail / 3;
// 여러개일경우 다른 selector 을 확인하기위한 상위 dom 으로 이동
var p = e.target.parentElement;
// 몇번째 dom 인지 저장
var index = Array.prototype.indexOf.call(p.children, e.target);
// 같은 위치의 돔목록 을 저장
var elmArr = e.target.parentElement.children;
// 지금의 스크롤 위치 저장
currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
// 다음위치의 좌표(기본이므로 현재의 Y 좌표 저장)
var NextTarget = currentScroll;
// 마우스휠 위로
if (delta > 0) {
// 맨처음 지점 제외
if (index > 0) {
// 이전 dom 의 index 번호
var no = (index - 1);
// 좌표위치 저장
NextTarget = elmArr[no].offsetTop;
}
}
// 마우스휠 아래로
else if (delta < 0)
{
// 맨마지막 지점 제외
if (index < elmArr.length - 1) {
// 다음 dom 의 index 번호
var no = (index + 1);
// 좌표위치 저장
NextTarget = elmArr[no].offsetTop;
}
}
// 애니메이션
// 필요없으면 바로 window.scrollTo(0, NextTarget);
// 에니메이션 초기화
clearInterval(tim);
// 애니메이션 실행
tim = setInterval(tran, 1);
// 애니메이션 function
function tran() {
// 이동속도 숫자가 작아질수록 느려짐
var speed = 5;
// 현재 스크롤과 이동후 스크롤이 같으면 정지시킨다
if (currentScroll == NextTarget) {
clearInterval(tran);
} else {
// 스크롤을 위로 올릴 경우
if (currentScroll - speed > NextTarget)
{
currentScroll -= speed;
}
// 스크롤을 내일 경우
else if (currentScroll + speed < NextTarget)
{
currentScroll += speed;
}
// 스크롤이 속도로 지정된 변수보다 작을 경우 강제적으로 맞춰준다
else
{
currentScroll = NextTarget;
}
// 스크롤위치 변경
window.scrollTo(0, currentScroll);
}
}
}
</script>
</head>
<body>
<div class="box" style="background-color:red;">1</div>
<div class="box" style="background-color:orange;">2</div>
<div class="box" style="background-color:yellow;">3</div>
<div class="box" style="background-color:green;">4</div>
<div class="box" style="background-color:blue;">5</div>
<div class="box" style="background-color:indigo;">6</div>
<div class="box" style="background-color:violet;">7</div>
</body>
</html>
JQuery 한화면 단위 Mouse Wheel 이동 를 참고해서 그냥 Javascript 로...
라벨:
웹,
HTML,
Javascript
19. 4. 4.
이미지 파일 업로드 전 미리보기
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8"/>
<title>업로드 미리보기(추가버전)</title>
<style>
ul,li{ margin: 0; padding: 0;}
li{ list-style: none; width: 100%; display: inline-block; margin: 0.3em 0;}
.preview{ display: inline-block; width: 82px; height: 82px; float: left;}
.imgUpBtn{ display: inline-block; padding: 1.9em 2em; background-color:cornflowerblue; color: #fff; font-size: 16px; font-weight: 700; border: 0;}
.ImgRemoveBtn{ display: inline-block; padding: 1.9em 2em; color: #fff; background-color: #555;font-size: 16px; font-weight: 700;}
#ImgAddBtn{ padding: 1.9em 2em; color: #fff; background-color:coral; font-weight: 700;}
</style>
<script>
// 미리보기 목록 추가
function fileinputAdd(){
// 미리보기 리스트 추가
var li = "<img class=\"preview\" alt=\"\" />"
+ "<button class=\"imgUpBtn\">이미지 업로드</button>"
+ "<a class=\"ImgRemoveBtn\">삭제</a>";
var ul = document.getElementById("image-list");
ul.innerHTML += "<li>"+li+"</li>";
// 인풋 파일 생성
var fileinput = document.createElement("INPUT");
fileinput.setAttribute("type", "file");
fileinput.setAttribute("class", "files");
fileinput.setAttribute("name", "files[]");
fileinput.setAttribute("accept", "image/jpeg, image/png");
fileinput.setAttribute("style", "display:none;");
document.body.appendChild(fileinput);
// 삭제도 있어야될것 같아서 넣어봄
var removeBtn = document.getElementsByClassName("ImgRemoveBtn");
for(var i = 0; i < removeBtn.length; i++){
removeBtn[i].setAttribute("onclick","fileinputRemove("+i+");");
}
// 새로 생성되면서 파일 미리보기 다시 로드
previewInputReload();
// 이미지 업로드 버튼 기능 다시 로드
fileimgUpBtnReload();
}
// 미리보기 개별 삭제
function fileinputRemove(index){
var li = document.querySelectorAll('#image-list li')[index];
var input = document.getElementsByClassName('files')[index];
var removeBtn = document.getElementsByClassName("ImgRemoveBtn")[index];
if(li != undefined){
input.remove();
li.remove();
removeBtn.remove();
li = document.querySelectorAll('#image-list li');
for(var i = 0; i < li.length; i++){
var removeBtn = document.getElementsByClassName("ImgRemoveBtn")[i];
removeBtn.setAttribute("onclick","fileinputRemove("+i+");");
}
}
// 삭제되면되면 파일 미리보기 다시 로드
previewInputReload();
// 삭제후 이미지 업로드 버튼 기능 다시 로드
fileimgUpBtnReload();
}
// 파일 업로드기능 function 연결하는 부분
function fileimgUpBtnReload(){
var uploadBtn = document.getElementsByClassName('imgUpBtn');
for(var i = 0; i <uploadBtn.length; i++){
uploadBtn[i].setAttribute("onclick","uploadFile("+i+");");
}
}
// 이미지 업로드 버튼 눌를때 해당 파일인풋 대신 클릭
function uploadFile(index){
document.getElementsByClassName("files")[index].click();
}
// 이미지 미리보기 관련 다시 로드
function previewInputReload(){
var input = document.getElementsByClassName('files');
for(var i=0; i< input.length;i++){
input[i].setAttribute("onchange","document.getElementsByClassName('preview')["+i+"].src=window.URL.createObjectURL(this.files[0])");
}
}
// window 로드시
window.onload = function(){
// image-list 에 기본적으로 파일 업로드 하나는 넣어줌..
fileinputAdd();
var AddBtn = document.getElementById("ImgAddBtn");
// 파일 추가 클릭 이벤트 생성
AddBtn.addEventListener("click", function(){
fileinputAdd();
},false);
}
</script>
</head>
<body>
<button id="ImgAddBtn">파일추가</button>
<ul id="image-list"></ul>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8"/>
<title>업로드 미리보기(단딜(multiple) 버전)</title>
<style>
#image-list > img{ width: 82px; height: 82px; margin: 1px; display: inline-block;}
#imgUpBtn{ padding: 1.9em 2em; color: #fff; background-color:coral; font-weight: 700;}
</style>
<script>
// window 로드시
window.onload = function(){
var UpBtn = document.getElementById("imgUpBtn");
// 파일 추가 클릭 이벤트 생성
UpBtn.addEventListener("click", function(){
var fileinput = document.createElement("INPUT");
fileinput.setAttribute("type", "file");
fileinput.setAttribute("class", "files");
fileinput.setAttribute("name", "files[]");
fileinput.setAttribute("id", "imgUpInput");
fileinput.setAttribute("multiple", "multiple");
fileinput.setAttribute("accept", "image/jpeg, image/png");
fileinput.setAttribute("style", "display:none;");
// 파일 변동시 처리
fileinput.setAttribute("onchange","previewImages(this.files);");
document.body.appendChild(fileinput);
// input file 를 눌러줌
document.getElementById("imgUpInput").click();
},false);
}
function previewImages(obj){
for(var i = 0; i < obj.length; i++){
var img = document.createElement("img");
img.setAttribute("src", window.URL.createObjectURL(obj[i]));
var list = document.getElementById("image-list");
list.appendChild(img);
}
}
</script>
</head>
<body>
<button id="imgUpBtn">이미지 업로드</button>
<div id="image-list"></div>
</body>
</html>
16. 10. 24.
JQuery 한화면 단위 Mouse Wheel 이동
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>MouseWheel</title>
<style type="text/css">
html,body{ margin:0; padding:0; width:100%; height:100%;}
.box{ width:100%; height:100%; position:relative; color:#ffffff; font-size:24pt;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var elm = ".box";
$(elm).each(function (index) {
// 개별적으로 Wheel 이벤트 적용
$(this).on("mousewheel DOMMouseScroll", function (e) {
e.preventDefault();
var delta = 0;
if (!event) event = window.event;
if (event.wheelDelta) {
delta = event.wheelDelta / 120;
if (window.opera) delta = -delta;
}
else if (event.detail)
delta = -event.detail / 3;
var moveTop = $(window).scrollTop();
var elmSelecter = $(elm).eq(index);
// 마우스휠을 위에서 아래로
if (delta < 0) {
if ($(elmSelecter).next() != undefined) {
try{
moveTop = $(elmSelecter).next().offset().top;
}catch(e){}
}
// 마우스휠을 아래에서 위로
} else {
if ($(elmSelecter).prev() != undefined) {
try{
moveTop = $(elmSelecter).prev().offset().top;
}catch(e){}
}
}
// 화면 이동 0.8초(800)
$("html,body").stop().animate({
scrollTop: moveTop + 'px'
}, {
duration: 800, complete: function () {
}
});
});
});
}
</script>
</head>
<body>
<div class="box" style="background-color:red;">1</div>
<div class="box" style="background-color:orange;">2</div>
<div class="box" style="background-color:yellow;">3</div>
<div class="box" style="background-color:green;">4</div>
<div class="box" style="background-color:blue;">5</div>
<div class="box" style="background-color:indigo;">6</div>
<div class="box" style="background-color:violet;">7</div>
</body>
</html>
ie 일 경우 ie 6 이하의 브라우저에서 안됨 이때에는 head에<meta http-equiv="X-UA-Compatible" content="IE=edge">
를 넣어줘야한다
추가 (좌우)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>MouseWheel</title>
<style type="text/css">
html,body{ margin:0; padding:0; width:100%; height:100%;}
.boxwrap{ display: table; table-layout: fixed; width: 700%; height: 100%; table-layout: fixed;}
.box{ display: table-cell;position:relative; color:#ffffff; font-size:24pt;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var elm = ".box";
$(elm).each(function (index) {
// 개별적으로 Wheel 이벤트 적용
$(this).on("mousewheel DOMMouseScroll", function (e) {
e.preventDefault();
var delta = 0;
if (!event) event = window.event;
if (event.wheelDelta) {
delta = event.wheelDelta / 120;
if (window.opera) delta = -delta;
}
else if (event.detail)
delta = -event.detail / 3;
var moveTop = $(window).scrollLeft();
var elmSelecter = $(elm).eq(index);
// 마우스휠을 위에서 아래로
if (delta < 0) {
if ($(elmSelecter).next() != undefined) {
try{
moveTop = $(elmSelecter).next().offset().left;
}catch(e){}
}
// 마우스휠을 아래에서 위로
} else {
if ($(elmSelecter).prev() != undefined) {
try{
moveTop = $(elmSelecter).prev().offset().left;
}catch(e){}
}
}
// 화면 이동 0.8초(800)
$("html,body").stop().animate({
scrollLeft: moveTop + 'px'
}, {
duration: 800, complete: function () {
}
});
});
});
}
</script>
</head>
<body>
<div class="boxwrap">
<div class="box" style="background-color:red;">1</div>
<div class="box" style="background-color:orange;">2</div>
<div class="box" style="background-color:yellow;">3</div>
<div class="box" style="background-color:green;">4</div>
<div class="box" style="background-color:blue;">5</div>
<div class="box" style="background-color:indigo;">6</div>
<div class="box" style="background-color:violet;">7</div>
</div>
</body>
</html>
좀 복잡한 방법 : Jquery 한화면 단위 Mouse Wheel 이동 (응용)
라벨:
웹,
HTML,
Javascript,
JQuery
피드 구독하기:
글 (Atom)