개발

삼항연산자, input 응용 예제! 본문

Frontend/JavaScript

삼항연산자, input 응용 예제!

Study 2021. 3. 5. 23:33

1단계!

1버튼으로 x축 50~500 사이로만 왔다갔다 하게하기! 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
img{
    position: absolute;
    top: 50px;
    left: 50px;
}
</style>
<script>
var flag=true;
var x=50;
function moveFunc(){
    (flag)? x+=50:x-=50;
    document.querySelector("img").style.left=x+"px";
    document.querySelector("#txt").value=x;
    ((x==500)||(x==50))? flag=!flag:0;
}
</script>
</head>
<body>
    <button onClick="moveFunc()">move!</button>
    X값<input type="parseInt" value=50 id="txt">
    <img src="../images/mushroom.png" width="100px">
</body>
</html>
cs

 

 

 

2단계!!

 

input 입 출력 응용 좌표 입력!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
img{
    position: absolute;
    top: 50px;
    left: 50px;
}
</style>
<script>
var flag=true;
var x=50;
function moveFunc(){
    x=document.querySelector("#txt").value;
    x=parseInt(x);
    (x>=500)? flag=false:0;
    (x<=50)? flag=true:0;
    (flag)? x+=50:x-=50;
    document.querySelector("img").style.left=x+"px";
    document.querySelector("#txt").value=x;
}
</script>
</head>
<body>
    X값<input type="text" value=50 id="txt">
    <button onClick="moveFunc()">move!</button>
    <img src="../images/mushroom.png" width="100px">
</body>
</html>
cs

 

 

 

 

 

 

3단계! 

 

입력가능 범위 지정하기!!

if문으로는 단 한줄인데 삼항연산자로 넣으려니 상당히 고되네요..  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
img{
    position: absolute;
    top: 50px;
    left: 50px;
}
</style>
<script>
var flag=true;
var x=50;
function moveFunc(){
    var n=document.querySelector("#txt").value;
    (n<50||n>500)? alert("범위지켜라"): x=document.querySelector("#txt").value;
    (n<50||n>500)? 0: x=parseInt(x);
    (n<50||n>500)? 0:(x>=500)? flag=false:0;
    (n<50||n>500)? 0: (x<=50)? flag=true:0;
    (n<50||n>500)? 0: (flag)? x+=50:x-=50;
    (n<50||n>500)? 0document.querySelector("img").style.left=x+"px";
    (n<50||n>500)? 0document.querySelector("#txt").value=x;
}
</script>
</head>
<body>
    X값<input type="text" value=50 id="txt">
    <button onClick="moveFunc()">move!</button>
    <img src="../images/mushroom.png" width="100px">
</body>
</html>
cs