document.title, document.body 을 호출 가능 (console 창에서)

document는 우리가 javascript 에서 HTML에 접근할 수 있는 방법이다. 

document는 브라우저에서 그냥 사용할 수 있는 object임.

 

document.getElementById("title")

getElementById => string을 전달받는 함수 

 

const title = document.getElementById("title") 
#getElementById는 HTML에서 id를 통해 element를 찾아준다.

console.dir(title)
<body>
    <h1 id="title">Grab me!</h1>
    <script src="app.js"></script>
</body>

HTML을 가지고 오는거지만, 그걸 JavaScript에서 하고 있음.

JavaScript는 이 HTML element를 가지고 오지만, HTML 자체를 보여주지는 않음.

 

 

element를 찾고 나면 그 HTML에서 뭐든지 바꿀 수 있음. 

const title = document.getElementById("title")

title.innerText = "Got you!" # element의 innerText를 바꿀 수도 있음.

console.log(title.id)         # element의 id와 className을 가져오는 것도 가능.
console.log(title.className)

 

따라서 우리는 이제 HTML에서 항목들을 가지고 와서 JavaScript를 통해 항목들을 변경할 수 있음.

 

예를 들어, 우리가 Hello DS처럼 유저에서 Hello라고 말하려면 우리는 HTML에서 title을 가지고 와야하고 유저명 또한 가져와서 해당 title 안에 넣어줘야함. 

' > 자바스크립트' 카테고리의 다른 글

자바스크립트 (2-3 return, prompt, if)  (0) 2023.03.16
자바스크립트 (2 - 2 object, function)  (2) 2023.03.16
자바스크립트 (2 - 1)  (2) 2023.03.16
자바스크립트 (1 - 준비)  (0) 2023.03.13

Anaconda(Miniconda) 플랫폼 : 다양한 데이터 분석 패키지를 지원하는 플랫폼

Jupyter Notebook : 웹 브라우저 기반 코딩 결과를 빠르게 확인할 수 있는 에디터

 

conda create -n (자기가 하고 싶은 이름) python=3.7

이런 식으로 가상환경 설치해줌.

 

가상환경을 활성화 시키기 

conda activate (자기가 하고 싶은 이름)

 

가상환경을 비활성화 시키기

conda deactivate 

 

필요한 거 설치

pip install numpy

pip install pandas matplotlib jupyter notebook

밑줄 친 부분은 꼭 가상환경에서 설치해야함.

 

 

'프로그래밍 > Python' 카테고리의 다른 글

Python 문자열 정렬, set  (0) 2023.10.08
Python zip, enumerate 함수 사용  (2) 2023.10.08
Python 비트 연산자 정리  (0) 2023.10.07
파이썬 매개변수 기본값 설정  (0) 2023.10.06
파이썬 (~while)  (0) 2023.04.25
# 대화창 만들기
"""
print("안녕하세요?")
name = input("이름을 말해주세요. ")
age = input("나이는 어떻게 되시나요? ")
print()

print("입력하신 정보는 \n이름은 {}, 나이는 {}입니다." .format(name, age))
print()

reply = input("맞으면 '예', 틀리면 '아니오'라고 입력해주세요. ")

if reply == "예":
    print("반갑습니다. {}씨 !!".format(name))
else :
    print('잘못된 정보입니다. ')
"""

# 온도 계산기
"""
celsius = int(input("섭씨 온도를 입력하세요 : "))
fahrenheit = (9/5) * celsius + 32

print("섭씨 {}도는 화씨 {:.0f}도입니다.".format(celsius, fahrenheit))
"""

# 몫과 나머지 계산
"""
print("두 개의 정수를 입력하세요.")

a = int(input())
b = int(input())

print("{} / {} 의 몫은 {}".format(a,b,a//b))
print("{} / {} 의 나머지는 {}".format(a,b,a%b))
"""

# 소금물의 농도 구하기
"""
print("소금물의 농도를 구하는 프로그램입니다.")

salt = float(input("소금의 양은 몇 g입니까? "))
water = float(input("물의 양은 몇 g입니까? "))

concentration = salt / (salt + water) * 100

print("소금물의 농도: {}".format(concentration))
"""

# BMI 구하기
"""
print("BMI를 구하는 프로그램입니다.")

a = input(" 계속하려면 아무키나 누르세요...")

height = float(input("키(cm) : "))
weight = float(input("몸무게(kg) : "))

BMI = weight/(height*0.01)**2

print("당신의 BMI : {:.2f}".format(BMI))
"""

# 성적처리 결과 출력하기
"""
name = input()
kor, math, music = int(input()),int(input()),int(input())
avg = (kor + math + music) / 3

print('\n"%s"님 성적 처리 결과입니다' % name)
print('-' * 30)
print('%s\t%s\t%s'%(" 과목","점수", "평균과의 차이"))
print('-' * 30)
print('국어 :{}  {:+5.1f}'.format(kor,kor-avg))
print('수학 :{}  {:5.1f}'.format(math,math-avg))
print('음악 :{}  {:5.1f}'.format(music,music-avg))
print('-' * 30)
print('평균 >> %5.1f' % avg)
"""

# 다항함수의 결과를 구하는 프로그램
"""
x, fx = 0, 0

x = int(input("x의 값을 입력하세요 : "))

fx = x**5-4*x**2-2*x+1/13
print("f({}) = {:.2f}".format(x, fx))
"""

# 동전 교환 프로그램
"""
w500, w100, w50, w10 = 0, 0, 0, 0

money = int(input("교환할 돈은 얼마?"))

w500 = money // 500
w100 = (money - 500*w500) // 100
w50 = (money - 500*w500 - 100*w100) // 50
w10 = (money - 500*w500 - 100*w100 - 50*w50) // 10
a = money % 10

print("500원의 개수: {}개\n100원의 개수: {}개\n50원의 개수: {}개\n10원의 개수: {}개\n바꾸지 못한 잔돈: {}원".format(w500,w100,w50,w10,a))
"""

# 윤년 계산 프로그램
"""
year = int(input("연도를 입력하세요 : "))

if year % 4 == 0 and year % 100 != 0:
    print("{}년은 윤년입니다.".format(year))

elif year % 400 == 0:
    print("{}년은 윤년입니다.".format(year))

else:
    print("{}년은 윤년이 아닙니다.".format(year))
"""

# 간단한 산술 계산기 프로그램
"""
x, y, op = 0, 0, ''

x = int(input("첫 번째 수를 입력하세요: "))
op = input("계산할 연산자를 입력하세요: ")
y = int(input("두 번째 수를 입력하세요: "))

if op == "+":
    total = x + y
    print("{} {} {} = {} 입니다.".format(x,op,y,total))

elif op == "-":
    total = x - y
    print("{} {} {} = {} 입니다.".format(x,op,y,total))

elif op == "*":
    total = x * y
    print("{} {} {} = {} 입니다.".format(x,op,y,total))

elif op == "/":
    total = x / y
    print("{} {} {} = {:.2f} 입니다.".format(x,op,y,total))
    
elif op == "%":
    total = x % y
    print("{} {} {} = {} 입니다.".format(x,op,y,total))

elif op == "//":
    total = x // y
    print("{} {} {} = {} 입니다.".format(x,op,y,total))

elif op == "**":
    total = x ** y
    print("{} {} {} = {} 입니다.".format(x,op,y,total))

else:
    print("알 수 없는 연산자입니다.")
"""

# 두 점 사이의 거리 구하기
"""
x1 = int(input("x1:"))
y1 = int(input("y1:"))
x2 = int(input("x2:"))
y2 = int(input("y2:"))

distance = ((x1-x2)**2 + (y1-y2)**2)**0.5

print("두 점 사이의 거리= {:.2f}".format(distance))
"""

# 놀이공원 입장료 구하기
"""
fee = 30000
age = int(input("나이 입력: "))

if age < 8:
    print("입장료는 무료입니다.")

elif age < 15 and age >= 8:
    print("입장료는 {}원입니다.".format(int(fee-fee*0.2)))

elif age >= 65:
    print("입장료는 {}원입니다.".format(int(fee-fee*0.5)))

else:
    print("입장료는 {}원입니다.".format(fee))
"""

# 합격 또는 불합격 표현하기
"""
first, second, interview, avg = 0, 0, 0, 0

first = int(input('1차 점수는?'))
second = int(input('2차 점수는?'))
interview = int(input('면접 점수는?'))

avg = (first + second + interview) / 3

if avg >= 80 and first >= 60 and second >= 60 and interview >= 60:
    print("축하합니다. 합격입니다.")

else:
    print('불합격입니다.')
"""

# 계절 출력하기
"""
month, season = 0, ''
month = int(input("월 입력 : "))

if month >= 3 or month <= 5:
    season = '봄'

elif month >= 6 or month <= 8:
    season = '여름'

elif month >= 9 or month <= 11:
    season = '가을'
    
elif month == 12 or month == 1 or month == 2:
    season = '겨울'

else:
    print("잘못된 월입니다.")

if month >= 1 and month < 12:
    print("{}월은 {}입니다.".format(month,season))
"""

# 자연수에서 n의 배수 출력하기
"""
cnt = 0
n = 1

while n < 100:
    if n % 7 == 0:
        print("%2d"%n, end = " ")
        n = n + 1
        cnt = cnt + 1
        if cnt % 5 == 0:
            print()

    else:
        n = n + 1
        pass

print("\n")
print("100 미만의 7의 배수는 {}개".format(cnt))
"""

# 조건이 참인 동안 반복하기
"""
count, height = 0, 0

while count != 10:
    height = float(input("키는? "))

    if height >= 140:
        count = count + 1
        print("Yes~")

    else:
        print("No~")

print("Go~ 출발합니다!")
"""

 

return

> function으로 무언가를 해서 function에서 결과값을 갖고 싶을 때

> function이 function 밖과 소통하는 방법 

> console.log()를 찍지 않아도 코드 내에서 반환값을 받을 수 있다.

> return을 하면 function은 작동을 멈추고 결과 값을 return하고 끝나버린다. 

 

1. return을 쓰지 않았을 때

const age = 21;
function caculateKrAge (ageOfForeigner) {
    ageOfForeigner + 2;
}

const krAge = caculateKrAge(age);

console.log(krAge);

결과값이 나오지 않는다. 

 

2. return을 쓴다면 

const age = 21;
function caculateKrAge (ageOfForeigner) {
    return ageOfForeigner + 2;
}

const krAge = caculateKrAge(age);

console.log(krAge);

결과값이 나온다. 

이 내용을 해석하자면

const age = 21;
function caculateKrAge (ageOfForeigner) {
    return ageOfForeigner + 2;
}

const krAge = caculateKrAge(age);

console.log(krAge);

// krAge가 function calculateKrAge가 되는데 
// function의 인수가 age고 age는 21
// 따라서 21이 function의 ageOfForeigner이 된다.
// 그렇게 하면 function 내에서 계산을 해서 21 + 2 를 해서 23을 만들고
// 이걸 다시 function을 시작한 곳에다가 보낸다.
// 그러면 calculateKrAge가 23이 되고
// 그걸 console로 찍는거다.

 

이 방법을 적용해서 하나 더 이해해보기

const calculator = {
    plus: function (a, b){
        return a + b;
    },
    minus: function (a, b){
        return a - b;
    },
    times: function (a, b){
        return a * b;
    },
    divide: function (a, b){
        return a / b;
    },
    power: function (a, b){
        return a ** b;
    },
};

const plusResult = calculator.plus(2, 3);
const minusResult = calculator.minus(plusResult, 10);
const timesResult = calculator.times(10, minusResult);
const divideResult = calculator.times(timesResult, plusResult);
const powerResult = calculator.power(divideResult, minusResult);

prompt

> 아주 오래된 방법

> prompt로 사용자에게 어떤 창을 띄워주고 사용자가 말하는 걸 저장할 수 있다.

 

const age = prompt("How old are you?");

console.log(age);

이런 창이 뜬다. 근데 이 방법은 아주 오래된 방법이라서 요즘에는 잘 안 쓴다고 한다.

 

어쨌든 여기다가 만약에 232323을 넣는다. 그러면 console 창에

이런 식으로 뜨는데 그런데 이것의 타입이 숫자일까?

이게 무슨 타입인지 알고 싶으면 typeof를 쓰면 된다.

console.log(typeof age);

//typeof 변수의 타입을 보는 거라서 
//변수가 무슨 타입인지 헷갈릴 때 사용하면 된다.

실행하면

string으로 뜬다. 

 

그렇다면 string을 number로 바꿀 수는 없을까? ("23" > 23 이런 식으로)

parseInt 를 사용하면 된다. 

console.log(typeof "15", typeof parseInt("15"));

그런데 parseInt() 이 괄호 사이에 "123" 과 같이 안 넣고 "dsdsd" 이런 식으로 넣으면 

NaN이 나오는데 이건 not a number 이라는 뜻으로 parseInt() 는 "123" 이런 형식의 string 만 숫자로 바꿔줄 수 있다. 

 

number인지 아닌지는 isNaN (< 해석하면 is not a number이라는 뜻)이라는 function을 통해서도 가능하다. 

const age = parseInt(prompt("How old are you?"));

console.log(isNaN(age));

// age를 prompt로 사용자에게 물어보고 얻는 답을 parseInt로 
// 변환하고
// console로 찍어보는데 그 전에 isNaN을 통해서 age가 number이 맞는지 확인한다.

이게 무슨 말이냐 하면 

실제로 저걸 구현해보면 

이런 식의 창이 나올텐데

거기서 내가 만약에 숫자 15를 넣는다고 하면

console 창에 다음과 같이 뜬다.

isNaN의 결과값은 boolean으로 나타난다. 

따라서 결과값이 숫자가 아니라면 true로 나타나고 숫자라면 false로 나타나는거다.

위의 결과는 숫자를 내가 입력했기 때문에 console 창에 결과로 false가 나온 것이다. 

 

if(condition)

> condition은 boolean이어야 한다.

const age = parseInt(prompt("How old are you?"));

console.log(isNaN(age));
/// isNaN(age) 는 boolean으로 값을 준다.
/// 따라서 condition에 들어가는 거 가능.

if (isNaN(age)) {
    console.log("Please write a number.")
} else {
 	console.log("Thank you for writing your age")
}

// 여기서 사용자가 숫자를 치면 console 창에 아무 것도 뜨지 않고, 문자를 치면 console 창에 Please write a number.
// if 문은 안에 있는 condition이 true면 활성화
// 그게 아니면 else로 넘어가서 실행

> else if로 condition을 하나 더 추가하면서 코드를 작성할 수도 있다.

const age = parseInt(prompt("How old are you?"));

if (isNaN(age)) {
    console.log("Please write a number.");
} else if(age < 18) {
    console.log("You are too young.")
} else {
    console.log("You can drink.")
}

해석 if

1.

 일단 입력하는 칸에다가 hahahahhah이걸 치면 parseInt가 number로 바꿔주지 못한 채로 if로 넘어간다.

그 age 값이 숫자가 맞는지 확인한다. hahahahhah는 숫자가 아니기 때문에 if 의 (condition)이 true. true기 때문에

Please write a number을 console 창에 띄운다. 

 

2.

 숫자 12를 입력했다면 isNaN 여기서 false가 되고 if가 false 이기 때문에 else if로 넘어가는데 이 때 12는 18보다 작기 때문에 True. You are too young. 을 console창에 띄운다.

 

3.

 숫자 23을 입력했다면 else if도 false이기 때문에 you can drink를 console 창에 띄운다. 그리고 else 쪽으로 넘어가서 

console 창에 You can drink.를 띄운다.

 

else if를 통해 18세 이상 50세 이하 이런 식으로 할 수도 있다.

else if(age >= 18 && age <= 50){
    console.log("You can drink.")

여기서 &&이 우리말로 하면 그리고(and) 라는 뜻으로 18세 이상 50세 이하 이렇게 해석하면 된다.

&&는 둘 다 true 여야만 그 else if 절이 true 라는 뜻이 되고 else if 코드가 실행된다.

&& 대신에 ||을 넣으면 또는(or) 이라는 뜻이다. 

||는 둘 다 true가 아니고 하나만 true 여도 그 코드가 실행된다.

 

정리하면 이렇게 된다.

true || true === true
false || true === true
true || false === true
false || false === false

true && true === true
true && false === false
false && true === false
false && false === false

 

총 복습

const age = parseInt(prompt("How old are you?"));

if (isNaN(age) || age < 0) {
    console.log("Please write a real positive number.");
} else if(age < 18) {
    console.log("You are too young.");
} else if(age >= 18 && age <= 50){
    console.log("You can drink.");
} else if(age > 50 && age <= 80){
    console.log("You should exercise.");
} else if(age === 100){    
    console.log("Wow, you are wise.")    // age가 100이 아니라면을 표현하고 싶으면 === 을 !==으로
} else if(age > 80){
    console.log("You can do whatever you want.");
}

Object

> 게임 같은 거를 생각하면 player 에다가 경험치, 이름, 인기도 이런 거를 설정할텐데

const playerName = "daesung"
const playerFat = "little bit"
const playerage = 23

이런 식으로 설정하면 번거롭다.  그래서 object 를 할 건데,

 

> object는 이런 식으로 설정

// 중괄호가 들어간다는 거 기억
// object 안과 밖의 규칙은 다르다. 밖에서는 = 을 사용하지만, 안에서는 : 을 사용
// 한 개의 특성(예, name : "daesung")을 설정하면 다른 특성도 올 수 있으니깐 그 뒤에는 ,를 사용한다.
// player의 name에 접근하고 싶을 때는 player.name 또는 player["name"]

const player = {
    name: "daesung",
    points: 10,
    fat: true,
}
console.log(player);
console.log(player.name);

 

object안의 내용물을 업데이트 하는 것도 가능함. 

const player = {
    name: "daesung",
    points: 10,
    fat: true,
}

player.fat = false;
console.log(player);

근데 여기서 의문점 

const 로 변수를 잡으면 데이터를 바꿀 수 없다고 했지 않나?

 - 맞는데 우리가 바꾼 건 player 라는 object 안에 있는 fat을 바꾼 거라서 상관이 없다. 만약 player 전체의 값을 바꿀려고 한다면 에러가 뜬다. 

 

추가도 가능하다.

const player = {
    name: "daesung",
    points: 10,
    fat: true,
}

// 별 다른 설정 없이 그냥 object를 불러서 내가 넣고 싶은 데이터 이름 값 넣으면 된다.
player.lastName = "sim";
console.log(player);

 

숫자를 더하는 것도 가능하다.

const player = {
    name: "daesung",
    points: 10,
    fat: true,
};
console.log(player);
player.lastName = "sim";

// 아래와 같이 코드를 쓰면 25라는 결과를 얻을 수 있다.
player.points = player.points + 15;
console.log(player.points);

 

 

fuction

> 반복해서 사용할 수 있는 코드 조각

> alert(), push() 등과 같이 괄호가 우리가 function을 실행시키는 방법 

function sayHello(){
    console.log("Hello my naem is C");
}

sayHello();

> argument는 function을 실행하는 동안 어떤 정보를 function에게 보낼 수 있는 방법

function sayHello(){
    console.log("Hello my naem is C");
}

// 해석: sayHello라는 함수를 누르고 그 함수에다가 "daesung"이라는 데이터를 보낸다.
sayHello("daesung");

 

그럼 어떻게 받느냐??

// function sayHello ()에 nameOfPerson을 넣었는데 이건 sayHello라는 함수로 보낸 데이터가 
// nameOfPerson이라는 variable 안에 저장된다는 것
// 그리고 nameOfPerson은 function sayHello() 안에 있기 때문에 function 안에서만 사용해야함.
// 만약 
// function sayHello(nameOfPerson){
//   	console.log(nameOfPerson);
// }
// console.log(nameOfPerson)을 쓴다면 출력되지 않으니 조심!!!
 
function sayHello(nameOfPerson){
    console.log(nameOfPerson);
}

sayHello("daesung");
sayHello("sim");
sayHello("ds");

이렇게 해서 출력을 하면 

이런 식으로 나온다. 

 

argument를 2개 설정할 수도 있다.

function sayHello(nameOfPerson, age){
    console.log(nameOfPerson, age);
}

sayHello("daesung", 10);
sayHello("sim", 23);
sayHello("ds", 21);

더 나아가서 이런 것들도 가능하다.

function sayHello(nameOfPerson, age){
    console.log("Hello my name is " + nameOfPerson + " and I'm " + age);
}

sayHello("daesung", 10);
sayHello("sim", 23);
sayHello("ds", 21);
function plus(firstNumber, secondNumber){
    console.log(firstNumber + secondNumber);
}
function divide(a, b){
    console.log(a/b);
}
plus(8, 60);
divide(98, 20);

 

그런데 console.log() 이런 식으로 하는 것처럼 player.sayHello() (player가 object일 때)와 같은 것도 가능하지 않을까?

가능하다.

// 코드 해석
//
// player를 object로 잡고 
// 설정할 function을 넣는데 형식은 sayHello : function() {} 
// 이런 식으로 그래서 만약에 player 안에 있는 fuction을 부를 때는 
// player.sayHello() 이런 식으로 부르고 이 funtion에다가 보내고 싶은
// argument를 적고 보낸다. 그럼 function 안에 있는 otherPersonName에 저장되어서
// function을 실행한다.

const player = {
    name: "daesung",
    sayHello: function (otherPersonName) {
        console.log("hello! " + otherPersonName + " nice to meet you!");
    },
};

player.sayHello("daesung");

숫자와 문자

> 자바스크립트는 숫자는 그대로 쓰면 인식한다.

> 문자는 " '', ' ' 이 안에다가 써야 한다. 문자로만 이루어진 텍스트를 string이라고 부른다.

 

변수 설정

> 변수 앞에 const (const 대신 let, var을 붙여줘도 됨.) 를 붙여주고 자신이 원하는 변수 이름을 설정하면 된다.

> 변수가 길 때 띄어쓰기를 해주고 싶으면 아래 코드 myName 과 같이 띄어쓰기 해주고 싶은 부분의 뒤에 문자를 대문자로히면 된다.

const a = 5;
const b = 2;

const myName = "daesung";

cf. const와 let의 차이점

> const 는 constant(상수)라는 것이고, constant 는 값이 바뀔 수 없다.

> let 은 새로운 것을 생성할 때 사용, 따라서 처음에 let으로 변수를 설정하면 따로 let을 앞에 안 해도 나중에 수정이 가능.

 

예시

1. let으로 myName을 변수로 설정할 때

const a = 5;
const b = 2;
let myName = "daesung";

console.log(a + b);
console.log(a * b);
console.log(a / b);
console.log("hello " + myName) ;

myName = "musung"

console.log("your new name is " + myName)

2. const 로 myName을 변수로 설정할 때.

const a = 5;
const b = 2;
const myName = "daesung";

console.log(a + b);
console.log(a * b);
console.log(a / b);
console.log("hello " + myName) ;

myName = "musung";

console.log("your new name is " + myName)

차이점을 분명하게 하자.

 

 

출력

> console.log () 를 통해서 브라우저의 console 창에 출력되는지 확인한다. 

console.log(a + b);
console.log(a * b);
console.log(a / b);
console.log("hello " + myName) ;

 

타입 

 

boolean

> true, false 두 가지가 있다.

 

null

> 아무 것도 없다는 상태, 비어있음

> 변수 안에 어떤 것이 없다는 상태를 확실히 하기 위해 쓴다.

const amIFat = null;
console.log(amIFat);

이렇게 되면 amIFat 은 아무 것도 없는 상태인거다.

 

undefined

> 값이 들어가지 않은 상태

let something;
console.log(something);

something이라는 공간은 있는데 그곳에 값이 들어가지 않은 것이다.

 

array

> 데이터를 나열할 수 있도록 해준다.

> array 는 [ ] 안에 자신이 원하는 데이터를 넣어주면 된다.

> 하나의 variable 안에 데이터의 list를 가지는 게 목적

 

const daysofweek = [mon , tue , wed , thu , fri , sat , sun] ;

const nonsense = [1, 2, "hello", false, null, true, undefined, "daesung"]

console.log(daysofweek, nonsense)

 

정렬 안의 5번째 데이터를 찾고 싶다면 아래와 같은 식으로 찾으면 된다. 

cf. 컴퓨터는 0부터 센다.

console.log(daysofweek[4])

 

array 안에 항목 하나를 추가하고 싶을 때

// () 안에다가 내가 원하는 데이터 입력하기
daysofweek.push()

 

 

자바스크립트가 없는 브라우저는 보기 힘들다. (그만큼 많다.)

자바스크립트 제대로 배워 놓으면 나중에 편하다.

 

 

시작하기 전에

 

HTML과 CSS는 조금 할 줄 알아야한다.

HTML이랑 CSS가 뭐고 어떤게 있는지만 알면 된다. 너무 자세하게 알 필요는 없다.

 

자바스크립트를 다루는 방법은 브라우저의 console을 사용하면 된다.

어떻게 하냐면

어디든지 웹 페이지에서 우클릭을 하고 제일 하단에 있는 검사를 누르면 

이런 화면이 뜨는데 저기서 빨간색으로 동그라미 한 곳을 들어가면 된다.

참고로 여기서 검은색 네모칸이 HTML 부분이고 노란색 네모칸이 CSS부분이다. 

console에 들어가면 이렇게 나오는데 여기서 코딩을 할 수는 있지만 한 줄씩 해야해서 번거롭다. 

그러니 VS code를 사용해서 하면 된다.

 

그럼 자바스크립트를 사용한 예시를 한번 보자.

<!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">
    <link rel="stylesheet" href="style.css">
    <title>Momentum</title>
</head>
<body>
    <script src="app.js"></script>
</body>
</html>

여기서 특징을 2가지 발견할 수 있다.

    <link rel="stylesheet" href="style.css">

> 미리 만들어둔 style.css를 html로 가져온다는 뜻이다.

<script src="app.js"></script>

> 미리 만들어둔 app.js을 html로 가져온다는 뜻이다.

 

vs code 전체로 보면

요런 식으로 되어 있다.

 

이렇게 하고 자바스크립트 본격적인 걸로 넘어간다.

HTML

 

태그

<div>구역</div>
<p>문단</p>
<h1>제목</h1>
<h2>소제목</h2>
<h3>h3~h6 h 뒷 숫자가 커질수록 글자 크기는 작아진다. </h3>
<a href="https://spartacodingclub.kr/"> 하이퍼링크 </a>    >>> href는 속성
<img src="https://s3.ap-northeast-2.amazonaws.com/materials.spartacodingclub.kr/free/logo_teamsparta.png" width="300"/>   >>> src는 속성
<input type="text">
<button>버튼입니다.</button>

 

선택자의 역할을 하는 class 와 id

1) 단 하나만 존재하는 요소를 표현하기 위한 방법 → id

2) 비슷한 종류의 요소를 묶어놓는 방법 → class

 

CSS

1) class로 이름표 달아주기

<h1 class="maintitle">제목</h1>

2) id로 이름표 달아주기

<h1 id="title">제목</h1>

3) 꾸며주기

<style></style> 부분에 이 부분을 넣어주면 된다.

.mytitle {
	color: blue;
}

4) 꾸며주기 (id로 잡힌 부분은 앞에 #을 붙여준다.)

#myuniquetitle {
	color: blue;
}

 

 

Github

1. 회원가입

2. 아래 빨간색 네모칸으로 되어 있는 New 버튼 클릭

3. Repository name에 자신이 원하는 이름 적고 밑에 Create repository 클릭

4. 파일을 새로 생성하거나 업로드하면 된다. (나는 만든 파일이 있어서 업로드 하겠다.)

5. choose your files 를 선택해서 자신의 파일을 옮겨주고 스크롤바를 내리면 commit changes 초록색 버튼이 있는데 그걸 클릭해주면 된다.

여기서 주의해야 할 점!!

html 파일을 불러올 때는 반드시 index.html로 가져와서 업로드해야한다.

 

6. 그리고 settings 클릭 

7. 그리고 pages 클릭

8. none을 클릭하고 main으로 바꾸고 save 클릭한다. 이렇게 하면 자신이 만든 웹페이지가 만들어지고 있다는 표시가 뜨는데, 조금만 기다려보자.

9. 조금만 기다렸다가 F5를 누르면 저렇게 내 웹페이지가 생성되었다고 뜬다.

주석

> ctrl(또는 command) + / (슬래시)

> 언제 사용하나

 1) 필요없어진 코드를 삭제하는 대신 임시로 작동하지 못하게 하고 싶을 때 사용

 2) 코드에 대한 간단한 설명을 붙여두고 싶을 때 사용 / 주석을 붙여놓으면, 브라우저/컴퓨터가 읽지 않는다.

 

파일분리

> <style> ~ </style> 부분이 너무 길어지면, 보기가 어렵다.

> 지금은 그다지 길지는 않지만 나중에 필요할 거 같으니 알아두자.

빨간색 네모칸이 style 부분인데 이 부분을 잘라낸다.

그리고 

파일을 하나 만들건데, 이름은 style.css로 한다.

style.css에 잘라낸 파일을 넣는다. 그렇게 잘했다면 

위와 같이 나온다.

<!-- style.css 파일을 같은 폴더에 만들고, head 태그에서 불러오기 -->
<link rel="stylesheet" type="text/css" href = "(css파일이름).css">

위와 같은 코드를 넣는다.

이렇게 하면 결과는??? 

저번에 했던 거와 똑같이 나온다.

 

부트스트랩 

> 예쁜 CSS를 미리 모아둔 것

> https://getbootstrap.com/docs/5.0/components/buttons/

 

Buttons

Use Bootstrap’s custom button styles for actions in forms, dialogs, and more with support for multiple sizes, states, and more.

getbootstrap.com

이 사이트에 들어가면 잘 만들어진 CSS 요소들을 사용할 수 있다. 

어떻게 하느냐 하면

클릭해서 들어가면 

이런 화면이 뜬다. 

여기서 저 이모티콘이 있는 곳을 보면 Examples 라고 되어있고 밑에 

<button type="button" class="btn btn-primary">Primary</button>

이런 형식으로 되어있는 코드들이 보일 것이다.

이 코드를 <body></body> 부분에 넣으면

이런 식으로 되는데

여기서 위에서 첫 번째 빨간색 네모칸이 바로 남이 만들어놓은 CSS코드를 가지고 오는 부분이다.

그리고 두 번째 빨간색 네모칸이 앞서 말한 코드이다.

그래서 결과물을 보면 

이런 식으로 나온다. 

 

' > 웹개발 종합반' 카테고리의 다른 글

html css 기본 + github 사용  (2) 2023.03.09
웹개발 1주차 복습 (폰트 적용)  (0) 2023.03.05
웹개발 1주차 복습 (CSS)  (1) 2023.03.05
웹개발 1주차 복습 (웹 브라우저, HTML)  (0) 2023.02.27
웹개발 4주차 (2)  (0) 2023.02.13

구글 폰트 적용하는 방법

 

이건 앞에서 했던 거에 비하면 굉장히 쉽다.

 

구글 폰트에 들어가서 

자신이 마음에 드는 폰트를 하나 고른다.

그리고 

그림에서 보는 바와 같이 

1번을 클릭하고 2번을 복사해서 html의 style 부분에다가 붙여준다.

하지만 이것만 한다고 해서 웹사이트의 폰트가 바뀌지 않는다. 

Use on the web 이라고 적혀있는 부분에서 스크롤바를 내리면 

동그라미 친 부분을 복사하고 

붙여주면 된다.

<!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>
        @import url('https://fonts.googleapis.com/css2?family=Gugi&family=Hahmlet:wght@400;500;600;700&family=Nanum+Brush+Script&display=swap');

        * {
            font-family: 'Gugi', cursive;
            font-family: 'Hahmlet', serif;
            font-family: 'Nanum Brush Script', cursive;
        }

        .mytitle {
            background-color: green;

            width: 300px;

            border-radius: 10px;
            color: white;

            text-align: center;

            padding: 30px 0px 0px 0px;

            background-image: url('https://www.ancient-origins.net/sites/default/files/field/image/Agesilaus-II-cover.jpg');
            background-position: center;
            background-size: cover;
        }

        .wrap {
            width: 300px;
            margin: 20px auto 0px auto;
        }
    </style>
</head>

<body>
    <div class="wrap">
        <div class="mytitle">
            <h1>로그인 페이지</h1>
            <h5>아이디, 비밀번호를 입력하세요</h5>
        </div>
        <p>ID : <input type="text" /></p>
        <p>PW : <input type="text" /></p>
        <button>로그인하기</button>
    </div>
</body>

</html>

여기서 style 부분을 유심히 살펴보면 복붙하라고 한 부분이 보일거다.

근데 여기서 *{} 이렇게 돼있는 곳이 보일텐데

이건 폰트를 전체에 적용한다는 뜻이다.

그리고 코딩에서 *이 등장하면 모두 다 라는 뜻이니깐 참고하자.

 

그냥 부분 적용하고 싶으면 

*{} 대신 .mytitle{} 치고 {} 안에 *{}의 {} 안에 넣을려고 했던 걸 넣으면 된다.

말이 어렵다. 그냥 보자.

<!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>
        @import url('https://fonts.googleapis.com/css2?family=Gugi&family=Hahmlet:wght@400;500;600;700&family=Nanum+Brush+Script&display=swap');


        .mytitle {
            background-color: green;

            width: 300px;

            border-radius: 10px;
            color: white;

            text-align: center;

            padding: 30px 0px 0px 0px;

            background-image: url('https://www.ancient-origins.net/sites/default/files/field/image/Agesilaus-II-cover.jpg');
            background-position: center;
            background-size: cover;

            font-family: 'Gugi', cursive;
            font-family: 'Hahmlet', serif;
            font-family: 'Nanum Brush Script', cursive;
        }

        .wrap {
            width: 300px;
            margin: 20px auto 0px auto;
        }
    </style>
</head>

<body>
    <div class="wrap">
        <div class="mytitle">
            <h1>로그인 페이지</h1>
            <h5>아이디, 비밀번호를 입력하세요</h5>
        </div>
        <p>ID : <input type="text" /></p>
        <p>PW : <input type="text" /></p>
        <button>로그인하기</button>
    </div>
</body>

</html>

위의 사진과 아래 사진을 비교하면 확실히 차이가 난다.

+ Recent posts