분류 전체보기 (358)

💻 Programming/CSS

[CSS] 9. Image ( 이미지 관련 설정 )

 

이번에는 CSS 를 이용한 이미지 관련 속성을 설정하는 방법에 대해서 알아보도록 하겠습니다. 

  • The border property is used to set the width of an image border.

  • The height property is used to set the height of an image.

  • The width property is used to set the width of an image.

  • The -moz-opacity property is used to set the opacity of an image.

image border 속성

The border property of an image is used to set the width of an image border. This property can have a value in length or in %.

A width of zero pixels means no border.

Here is the example:

<img style="border:0px;" src="/images/css.gif" />
<br />
<img style="border:3px dashed red;" src="/images/css.gif" />

결과는 아래와 같습니다.

CSS Logo

 

 

image height 속성

The height property of an image is used to set the height of an image. This property can have a value in length or in %. While giving value in %, it applies it in respect of the box in which an image is available.

Here is the example:

<img style="border:1px solid red; height:100px;" 
        src="/images/css.gif" />
<br />
<img style="border:1px solid red; height:50%;" 
        src="/images/css.gif" />

결과는 아래와 같습니다.


 

 

image width 속성

The width property of an image is used to set the width of an image. This property can have a value in length or in %. While giving value in %, it applies it in respect of the box in which an image is available.

Here is the example:

<img style="border:1px solid red; width:100px;" 
        src="/images/css.gif" />
<br />
<img style="border:1px solid red; width:100%;" 
        src="/images/css.gif" />

결과는 아래와 같습니다.


 

 

-moz-opacity 속성

 -moz-opacity 속성은 이미지의 opacity를 설정하기위한 속성입니다. 이 속성은 Mozilla에서 이미지의 투명도를 설정하기 위한 것입니다. IE 는 filter:alpha(opacity=x) 를 사용하죠.

Mozilla에서 (-moz-opacity:x) 속성을 사용할 때 x 값은 0.0 에서 1.0 을 지정할 수 있습니다. 숫자가 낮을 수록 더 투명해지죠.  

In IE (filter:alpha(opacity=x)) x can be a value from 0 - 100. A lower value makes the element more transparent.

Here is the example:

<img style="border:1px solid red;-moz-opacity:0.4;filter:alpha(opacity=40);opacity:0.4;" src="/images/css.gif" />

결과는 아래와 같습니다.

 

 

 

 

 

 

 

 

Reference : http://www.tutorialspoint.com/css/css_images.htm

 

 

 

 

 

'💻 Programming > CSS' 카테고리의 다른 글

[CSS] 11. Table ( 테이블 설정 )  (0) 2016.06.12
[CSS] 10. Links ( 링크 설정 )  (0) 2016.06.12
[CSS] 8. Text ( 텍스트 설정 )  (0) 2016.06.12
[CSS] 7. Fonts ( 폰트 설정 )  (0) 2016.06.12
[CSS] 6. Background ( 배경 설정 )  (0) 2016.06.12

💻 Programming/CSS

[CSS] 8. Text ( 텍스트 설정 )

이번에는 CSS 속성을 이용해서 텍스트를 조작하는 방법에 대해서 알아보겠습니다.

  • The color property is used to set the color of a text.

  • The direction property is used to set the text direction.

  • The letter-spacing property is used to add or subtract space between the letters that make up a word.

  • The word-spacing property is used to add or subtract space between the words of a sentence.

  • The text-indent property is used to indent the text of a paragraph.

  • The text-align property is used to align the text of a document.

  • The text-decoration property is used to underline, overline, and strikethrough text.

  • The text-transform property is used to capitalize text or convert text to uppercase or lowercase letters.

  • The white-space property is used to control the flow and formatting of text.

  • The text-shadow property is used to set the text shadow around a text.

 

텍스트 색깔 설정

<p style="color:red;">
This text will be written in red.
</p>

결과는 아래와 같습니다.

This text will be written in red.

 

 

텍스트 방향 설정

Following is the example which demonstrates how to set the direction of a text. Possible values are ltr or rtl.

<p style="direction:rtl;">
This text will be renedered from right to left
</p>

결과는 아래와 같습니다.

This text will be renedered from right to left

 

 

문자 사이의 공간 설정

Following is the example which demonstrates how to set the space between characters. Possible values are normal or a number specifying space..

<p style="letter-spacing:5px;">
This text is having space between letters.
</p>

결과는 아래와 같습니다.

This text is having space between letters.

 

 

단어 사이의 공간 설정

Following is the example which demonstrates how to set the space between words. Possible values are normal or a number specifying space..

<p style="word-spacing:5px;">
This text is having space between words.
</p>

결과는 아래와 같습니다.

This text is having space between words.

 

 

텍스트 인덴트 설정

Following is the example which demonstrates how to indent the first line of a paragraph. Possible values are % or a number specifying indent space..

<p style="text-indent:1cm;">
This text will have first line indented by 1cm
and this line will remain at its actual position
this is done by CSS text-indent property.
</p>

결과는 아래와 같습니다.

This text will have first line indented by 1cm
and this line will remain at its actual position
this is done by CSS text-indent property.

 

 

텍스트 정렬 설정

Following is the example which demonstrates how to align a text. Possible values are left, right, center, justify..

<p style="text-align:right;">
This will be right aligned.
</p>
<p style="text-align:center;">
This will be center aligned.
</p>
<p style="text-align:left;">
This will be left aligned.
</p>

결과는 아래와 같습니다.

This will be right aligned.

This will be center aligned.

This will be left aligned.

 

 

텍스트 꾸밈 설정

Following is the example which demonstrates how to decorate a text. Possible values are none, underline, overline, line-through, blink..

<p style="text-decoration:underline;">
This will be underlined
</p>
<p style="text-decoration:line-through;">
This will be striked through.
</p>
<p style="text-decoration:overline;">
This will have a over line.
</p>
<p style="text-decoration:blink;">
This text will have blinking effect
</p>

결과는 아래와 같습니다.

This will be underlined

This will be striked through.

This will have a over line.

This text will have blinking effect

 

 

텍스트 대소문자 설정

Following is the example which demonstrates how to set the cases for a text. Possible values are none, capitalize, uppercase, lowercase..

<p style="text-transform:capitalize;">
This will be capitalized
</p>
<p style="text-transform:uppercase;">
This will be in uppercase
</p>
<p style="text-transform:lowercase;">
This will be in lowercase
</p>

결과는 아래와 같습니다.

This will be capitalized

This will be in uppercase

This will be in lowercase

 

 

텍스트 white-space 설정

Following is the example which demonstrates how white space inside an element is handled. Possible values are normal, pre, nowrap.

<p style="white-space:pre;">This text has a line break
and the white-space pre setting tells the browser to honor it
just like the HTML pre tag.</p>

결과는 아래와 같습니다. 

This text has a line break and the white-space pre setting tells the browser to honor it just like the HTML pre tag.

 

 

텍스트 그림자 설정

Following is the example which demonstrates how to set the shadow around a text. This may not be supported by all the browsers.

<p style="text-shadow:4px 4px 8px blue;">
If your browser supports the CSS text-shadow property, 
this text will have a  blue shadow.</p>

결과는 아래와 같습니다.

If your browser supports the CSS text-shadow property, this text will have a blue shadow.

 

 

 

 

Reference : http://www.tutorialspoint.com/css/css_text.htm

 

 

 

 

'💻 Programming > CSS' 카테고리의 다른 글

[CSS] 10. Links ( 링크 설정 )  (0) 2016.06.12
[CSS] 9. Image ( 이미지 관련 설정 )  (0) 2016.06.12
[CSS] 7. Fonts ( 폰트 설정 )  (0) 2016.06.12
[CSS] 6. Background ( 배경 설정 )  (0) 2016.06.12
[CSS] 5. Colors ( 색깔 )  (0) 2016.06.12

💻 Programming/CSS

[CSS] 7. Fonts ( 폰트 설정 )

이번 포스팅에서는 CSS를 이용해서 폰트를 설정하는 방법에 대해서 알아보도록 하겠습니다.

  • font-family 는 폰트를 변경하는 속성입니다. ( 돋움체, 굴림체 뭐 이런것들 있죠? ) 

  • font-style 는 폰트를 체를 변경하는 속성입니다. ( italic, oblique ) 

  • font-variant 는 대소문자를 설정하는 속성입니다.

  • font-weight 는 폰트의 굵기를 설정하는 속성입니다. ( bold, light ) 

  • font-size 는 폰트 사이즈를 설정하는 속성입니다.

  • font 는 폰트관련 모든 속성을 한번에 설정할 수 있는 한방 속성입니다.

 

폰트 패밀리 설정하기

설정 가능한 값은 모든 폰트 패밀리 값입니다. 예를들면 aria, serif와 같은 폰트 서체입니다.  

<p style="font-family:georgia,garamond,serif;">
This text is rendered in either georgia, garamond, or the default
serif font depending on which font  you have at your system.
</p>

결과는 아래와 같습니다.

This text is rendered in either georgia, garamond, or the default
serif font depending on which font you have at your system.

 

 

폰트 스타일 설정하기

설정 가능한 값은 normal, italic 그리고 oblique 입니다. 

<p style="font-style:italic;">
This text will be rendered in italic style
</p>

결과는 아래와 같습니다.

This text will be rendered in italic style

 

 

폰트 변종 설정하기

가능한 값은 normal small-caps가 있습니다.

<p style="font-variant:small-caps;">
This text will be rendered as small caps
</p>

결과는 아래와 같습니다.

This text will be renedered as small caps

 

 

폰트 두께 설정하기

폰트의 두께를 설정하는 속성입니다.

가능한 값은 normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900 이 있습니다.

<p style="font-weight:bold;">
This font is bold.
</p>
<p style="font-weight:bolder;">
This font is bolder.
</p>
<p style="font-weight:900;">
This font is 900 weight.
</p>

결과는 아래와 같습니다.

This font is bold.

This font is bolder.

This font is 900 weight.

 

 

폰트 사이즈 설정하기

가능한 값은 xx-small, x-small, small, medium, large, x-large, xx-large, smaller, larger, 그리고 픽셀값 또는 퍼센트 값입니다.

<p style="font-size:20px;">
This font size is 20 pixels
</p>
<p style="font-size:10pt;">
This font size is small
</p>
<p style="font-size:14pt;">
This font size is large
</p>

결과는 아래와 같습니다. 

This font size is 20 pixels

This font size is small

This font size is large

 

 

폰트 사이즈 adjust 설정하기

이번에는 폰트의 사이즈 adjust 설정을 하는 것이네요. 가능한 값은 모든 숫자값입니다.  

<p style="font-size-adjust:0.61;">
This text is using a font-size-adjust value.
</p>

결과는 아래와 같습니다.

This text is using a font-size-adjust value.

 

 

폰트 스트레치 설정

가능한 값은 normal, wider, narrower, ultra-condensed, extra-condensed, condensed, semi-condensed, semi-expanded, expanded, extra-expanded, ultra-expanded 가 있습니다. 이 속성은 여러분 컴퓨터에 있는 폰트가 

<p style="font-stretch:ultra-expanded;">
If this doesn't appear to work, it is likely that 
your computer doesn't have a condensed or expanded 
version of the font being used.
</p>

결과는 아래와 같습니다.

If this doesn't appear to work, it is likely that your computer doesn't have a condensed or expanded version of the font being used.

 

 

폰트 속성 한번에 설정하기

<p style="font:italic small-caps bold 15px georgia;">
Applying all the properties on the text at once.
</p>

결과는 아래와 같습니다

Applying all the properties on the text at once.

 

 

 

 

이상으로 폰트 관련 속성들에 대해서 알아보았습니다.

 

휴우~~~ 슬슬 CSS가 재미있어 지시나요? 지겨워지시나요?

 

이제 시작인데 말이죠 ㅋㅋㅋ

 

화이팅입니다~~ 

 

 

 

 

 

 

Reference : http://www.tutorialspoint.com/css/css_fonts.htm 

 

 

 

 

 

'💻 Programming > CSS' 카테고리의 다른 글

[CSS] 9. Image ( 이미지 관련 설정 )  (0) 2016.06.12
[CSS] 8. Text ( 텍스트 설정 )  (0) 2016.06.12
[CSS] 6. Background ( 배경 설정 )  (0) 2016.06.12
[CSS] 5. Colors ( 색깔 )  (0) 2016.06.12
[CSS] 4. Units ( 단위 )  (0) 2016.06.12

💻 Programming/CSS

[CSS] 6. Background ( 배경 설정 )

이번 포스팅에서는 각종 HTML 태그내에서 쓰이는 배경 관련 속성에 대해서 알아보도록 하겠습니다. 배경관련 속성에는 다음과 같은 것들이 있습니다.

  •  background-color 는 배경 색상을 설정하기 위한 속성입니다.

  •  background-image 는 배경 이미지를 설정하기 위한 속성입니다.

  •  background-repeat 는 배경 이미지의 반복 여부를 설정하기 위한 속성입니다.

  •  background-position 는 배경 이미지의 위치를 설정하기 위한 속성입니다.

  •  background-attachment 는 배경 이미지의 스크롤링을 설정하기 위한 속성입니다.

  •  background property is used as shorthand to specify a number of other background properties.

 

배경 색 설정하기

<p style="background-color:yellow;">
This text has a yellow background color.
</p>

This will produce following result:

This text has a yellow background color.

 

 

 

배경 이미지 설정하기

<table style="background-image:url(/images/pattern1.gif);">
<tr><td>
This table has background image set.
</td></tr>
</table>

 

 

배경 이미지 반복하기

<table style="background-image:url(/images/pattern1.gif); 
              background-repeat: repeat;">
<tr><td>
This table has background image which repeats multiple times.
</td></tr>
</table>

 

아래 예제는 배경 이미지를 세로로 반복시키는 예제입니다.

<table style="background-image:url(/images/pattern1.gif); 
              background-repeat: repeat-y;">
<tr><td>
This table has background image set which will repeat vertically.
</td></tr>
</table>

 

아래는 배경 이미지를 가로로 반복시키는 예제입니다.

<table style="background-image:url(/images/pattern1.gif); 
              background-repeat: repeat-x;">
<tr><td>
This table has background image set which will repeat horizontally.
</td></tr>
</table>

 

 

배경 이미지 위치 설정하기

배경 이미지를 왼쪽에서 100 픽셀 떨어뜨려서 위치시키는 예제입니다. 

<table style="background-image:url(/images/pattern1.gif); 
              background-position:100px;">
<tr><td>
Background image positioned 100 pixels away from the left.
</td></tr>
</table>

다으므 예제는 배경 이미지의 위치를 왼쪽에서 100 픽셀 그리고 위에서 200 픽셀 떨어진 곳에 위치시키는 예제입니다.

<table style="background-image:url(/images/pattern1.gif); 
              background-position:100px 200px;">
<tr><td>
This table has background image positioned 100
pixels away from the left and 200 pixels from the top.
</td></tr>
</table>

 

 

배경 이미지 고정 또는 스크롤 여부 설정하기

Background attachment determines whether a background image is fixed or scrolls with the rest of the page.

 

아래 예제는 배경이미지를 고정시키는 예제입니다. 

<p style="background-image:url(/images/pattern1.gif); 
              background-attachment:fixed;">
This parapgraph has fixed background image.
</p>

이번 예제는 스크롤링을 해주는 예제네요.

<p style="background-image:url(/images/pattern1.gif); 
              background-attachment:scroll;">
This parapgraph has scrolling background image.
</p>

 

 

배경 속성 한꺼번에 설정하기

background 속성은 여러개의 배경관련 속성을 한꺼번에 설정할 수 있도록 해줍니다. 

<p style="background:url(/images/pattern1.gif) repeat fixed;">
This parapgraph has fixed repeated background image.
</p>

 

 

 

 

 

Reference : http://www.tutorialspoint.com/css/css_backgrounds.htm 

 

 

 

 

 

 

 

 

'💻 Programming > CSS' 카테고리의 다른 글

[CSS] 8. Text ( 텍스트 설정 )  (0) 2016.06.12
[CSS] 7. Fonts ( 폰트 설정 )  (0) 2016.06.12
[CSS] 5. Colors ( 색깔 )  (0) 2016.06.12
[CSS] 4. Units ( 단위 )  (0) 2016.06.12
[CSS] 3. HTML에 CSS링크 - Associating Styles with HTML  (0) 2016.06.12

💻 Programming/CSS

[CSS] 5. Colors ( 색깔 )

 

CSS 에서 색깔을 지정하는 방법은 아래처럼 5가지 방법이 있습니다

FormatSyntaxExample
Hex Code#RRGGBBp{color:#FF0000;}
Short Hex Code#RGBp{color:#6A7;}
RGB %rgb(rrr%,ggg%,bbb%)p{color:rgb(50%,50%,50%);}
RGB Absolutergb(rrr,ggg,bbb)p{color:rgb(0,0,255);}
keywordaqua, black, etc.p{color:teal;}

 

아래에서 좀 더 자세히 알아보도록 하죠. 


1. CSS Colors - Hex Codes ( 16진수 RRGGBB 코드 )

16진수 코드로 표현할 때는 # 기호를 먼저 붙여주고 6자리의 RRGGBB 코드를 넣어주면 됩니다. RGB의 R은 빨강, G는 초록, B는 파랑입니다. RR이라는 것은 빨강을 나타내는 16진수 숫자를 말합니다. 예를 들면 00부터 FF까지의 값이 됩니다. GG와 BB역시 마찬가지입니다.

아래는 이렇게 16진수를 이용해서 색깔을 표시했을 때 어떻게 화면에 보여지는지를 보여주는 표입니다.


ColorColor HEX
 #000000
 #FF0000
 #00FF00
 #0000FF
 #FFFF00
 #00FFFF
 #FF00FF
 #C0C0C0
 #FFFFFF

 

 

CSS Colors - Short Hex Codes ( 16진수 RGB 코드 )

이번에는 좀 짧게 쓰는 RGB코드입니다. 위에서 RRGGBB로 쓰였던 것이 RGB로 줄어든 것이죠. 다른 점은 위 여섯자리 RRGGBB코드에서는 좀 더 세밀하게 색깔을 지정할 수 있는 반면 RGB코드에서는 좀 단순화된 색깔만 사용할 수 있다는 것이죠. 그 이유인즉슨 RR 두개로 표시할 수 이었던 빨간계열 색상을 R하나로만 나타내야하기 때문입니다. 예를들어 RGB코드의 #FFF에서 R을 나타내는 F는 RRGGBB의 RR로 변환한다면 FF가 되겠죠. 만약 RRGGBB의 RR값에 AD가 들어있었다고 하면 이것을 RGB로 표현할 수 있을 까요? 아닙니다. 표현할 수 없겠죠.
ColorColor HEX
 #000
 #F00
 #0F0
 #0FF
 #FF0
 #0FF
 #F0F
 #FFF

 

 

CSS Colors - RGB Values ( 10진수 RGB 코드 )

이 방법은 rgb( ) 속성을 이용합니다.  0 부터 255 숫자나 퍼센트를 값에 넣어줄 수 있습니다.

NOTE: 모든 브라우저가 rgb() 속성을 지원하는 것이 아니기 때문에 이 방법은 권장하지 않습니다. 

 

ColorColor RGB
 rgb(0,0,0)
 rgb(255,0,0)
 rgb(0,255,0)
 rgb(0,0,255)
 rgb(255,255,0)
 rgb(0,255,255)
 rgb(255,0,255)
 rgb(192,192,192)
 rgb(255,255,255)

 

예제 :  

<body style="color:rgb(0,0,255); background-color:rgb(0,255,0);"> 

Building Color Codes:

색깔 코드를 만들어주는 칼라 코드 빌더라는게 있네요.  HTML Color Code Builder.  

Browser Safe Colors:

아래 표는 브라우저의 영향이나 컴퓨터 디스플레이의 영향을 가장 안받는 그런 칼라표라고 하네요. 총 216 개의 색깔이 있습니다.

색깔을 보고 맘에드는거 코드 골라다가 쓰시면 됩니당. ^____^

 

0000000000330000660000990000CC0000FF
0033000033330033660033990033CC0033FF
0066000066330066660066990066CC0066FF
0099000099330099660099990099CC0099FF
00CC0000CC3300CC6600CC9900CCCC00CCFF
00FF0000FF3300FF6600FF9900FFCC00FFFF
3300003300333300663300993300CC3300FF
3333003333333333663333993333CC3333FF
3366003366333366663366993366CC3366FF
3399003399333399663399993399CC3399FF
33CC0033CC3333CC6633CC9933CCCC33CCFF
33FF0033FF3333FF6633FF9933FFCC33FFFF
6600006600336600666600996600CC6600FF
6633006633336633666633996633CC6633FF
6666006666336666666666996666CC6666FF
6699006699336699666699996699CC6699FF
66CC0066CC3366CC6666CC9966CCCC66CCFF
66FF0066FF3366FF6666FF9966FFCC66FFFF
9900009900339900669900999900CC9900FF
9933009933339933669933999933CC9933FF
9966009966339966669966999966CC9966FF
9999009999339999669999999999CC9999FF
99CC0099CC3399CC6699CC9999CCCC99CCFF
99FF0099FF3399FF6699FF9999FFCC99FFFF
CC0000CC0033CC0066CC0099CC00CCCC00FF
CC3300CC3333CC3366CC3399CC33CCCC33FF
CC6600CC6633CC6666CC6699CC66CCCC66FF
CC9900CC9933CC9966CC9999CC99CCCC99FF
CCCC00CCCC33CCCC66CCCC99CCCCCCCCCCFF
CCFF00CCFF33CCFF66CCFF99CCFFCCCCFFFF
FF0000FF0033FF0066FF0099FF00CCFF00FF
FF3300FF3333FF3366FF3399FF33CCFF33FF
FF6600FF6633FF6666FF6699FF66CCFF66FF
FF9900FF9933FF9966FF9999FF99CCFF99FF
FFCC00FFCC33FFCC66FFCC99FFCCCCFFCCFF
FFFF00FFFF33FFFF66FFFF99FFFFCCFFFFFF

 

 

 

 

 

Reference : http://www.tutorialspoint.com/css/css_colors.htm

 

 

 

 

💻 Programming/CSS

[CSS] 4. Units ( 단위 )

CSS 에서 사용하는 단위(Unit)

실제로 CSS로 뭔가를 하기전에 기본부터 다지고 가는게 좋겠죠?

그래서 이번에는 각종 속성값에 쓰이는 단위를 한번 알아보도록 하겠습니다.

 

CSS는 절대값을 나타내는 inches, centimeters, points 등등 뿐 아니라 상대값을 나타내는 percentages나 em 단위를 지원합니다. 이런 단위들은 자주 쓰이기 때문에 꼭 짚고 넘어가시는 것이 좋습니다.

 

다음은 단위와 단위에 대한 설명 및 사용 예제입니다. 

Unit Description Example
% 퍼센트 p {font-size: 16pt; line-height: 125%;}
cm 센티미터 div {margin-bottom: 2cm;}
em em 단위는 폰트의 사이즈와 동일하기 때문에 폰트사이즈를 12pt로 설정하면 각 em 단위는 12pt가 됩니다. 따라서 2em은 24pt가 되겠죠 p {letter-spacing: 7em;}
ex 이 값은 폰트의 x-높이값에 상대적인 값입니다. x-높이값은 해당 폰트의 소문자x값의 높이입니다. p {font-size: 24pt; line-height: 3ex;}
in 인치 p {word-spacing: .15in;}
mm 밀리미터 p {word-spacing: 15mm;}
pc picas라는 단위로 1 pica는 12 pt와 동일합니다; 따라서, 1인치에는 6 picas 가 존재합니다. p {font-size: 20pc;}
pt 포인트 단위로 1 pt는 72분의 1 인치입니다. body {font-size: 18pt;}
px 스크린 픽셀 단위 p {padding: 25px;}

 

example에 있는 내용을 css 파일에 작성해서 꼭!! 테스트해보세요~

 

 

 

 

Reference : http://www.tutorialspoint.com/css/css_measurement_units.htm 

 

'💻 Programming > CSS' 카테고리의 다른 글

[CSS] 6. Background ( 배경 설정 )  (0) 2016.06.12
[CSS] 5. Colors ( 색깔 )  (0) 2016.06.12
[CSS] 3. HTML에 CSS링크 - Associating Styles with HTML  (0) 2016.06.12
[CSS] 2. Syntax ( 문법, 사용법 )  (0) 2016.06.12
[CSS] 1. CSS란 ?  (0) 2016.06.11

 

CSS를 HTML문서에서 사용하는 방법은 네가지가 있습니다. 그 중에서도 가장 많이 쓰이는 방법은 inline CSS와 External CSS.

1. Embedded CSS - The <style> Element:

 <style> 요소를 이용해서 <head>...</head> 태그 내에 삽입하는 방법입니다. 

<head>
<style type="text/css" media="...">
Style Rules
............
</style>
</head>

속성:

 <style> 태그 내의 속성과 값은 아래와 같습니다.

Attribute Value Description
type text/css Specifies the style sheet language as a content-type (MIME type). This is required attribute.
media screen
tty
tv
projection
handheld
print
braille
aural
all
Specifies the device the document will be displayed on. Default value is all. This is optional attribute.

예제:

<head>
<style type="text/css" media="all">
h1{
color: #36C;
}
</style>
</head>

2. Inline CSS - The style Attribute:

인라인 CSS는 그냥 html태그 안에다가 써넣는 것을 말합니다. 가장 일반적으로 이렇게 사용하죠. 그러다가 따로 분리해서 관리해야되는 스타일이 있다면 이 다음에 설명한 External CSS를 이용하시면 됩니다. 

<element style="...style rules....">

속성:

Attribute Value Description
style style rules The value of style attribute is a combination of style declarations separated by semicolon (;).

예제:

<h1 style ="color:#36C;"> This is inline CSS </h1>

 

적용된 결과는 아래와 같습니다. 

This is inline CSS

3. External CSS - The <link> Element:

 <link> 요소를 이용하여 HTML 문서에 외부에서 정의된 CSS파일을 링크시킬 수가 있습니다. 

간단한 문법을 한번 볼까요??

<head>
<link type="text/css" href="..." media="..." />
</head>

속성:

 <link> 태그의 속성과 속성값들 입니다. 

Attribute Value Description
type text/css Specifies the style sheet language as a content-type (MIME type). This attribute is required.
href URL Specifies the style sheet file having Style rules. This attribute is a required.
media screen
tty
tv
projection
handheld
print
braille
aural
all
Specifies the device the document will be displayed on. Default value is all. This is optional attribute.

예제:

간단하게 mystyle.css 를 만들어 봅시다.

h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

 

이제 mystyle.css파일을 HTML문서에 링크를 시켜볼까요??

<head>
<link type="text/css" href="mystyle.css" media="all" />
</head>

4. Imported CSS - @import Rule:

@import 를 이용해서 <link> 요소처럼 스타일파일에 링크를 걸 수도 있습니다.  기본문법은 다음과 같습니다.

<head>
@import "URL";
</head>

 

아래처럼 url()메소드를 이용할 수도 있습니다.

<head>
@import url("URL");
</head>

예제:

<head>
@import "mystyle.css";
</head>

CSS Rules Overriding ( 규칙 오버라이딩 )

지금까지 CSS를 사용하는 네가지 방법에 대해서 알아보았습니다. 이 네가지 규칙이 동시에 적용이 된다면 어떤일이 벌어질까요??? 서로서로 오버라이딩을 하게 되는데 그 규칙을 한번 알아보도록 하겠습니다. 

  • inline 스타일이 다른 방법보다 항상 최우선시 적용됩니다.  

  • <style>...</style> 태그 내에 지정된 스타일들은 외부 CSS파일에 정의된 값들보다 우선권을 가집니다.

  • 외부 CSS파일은 항상 최저우선권을 가집니다. 

Handling old Browsers ( 구버전 브라우저 처리 )

구버전 브라우저 중에는 CSS를 지원하지 않는 브라우저가 있고 이런 브라우저를 사용하는 사용자들이 있을 수도 있겠죠. 만약 그럴경우에는 CSS를 적용하지 않도록 할 수 있습니다. 아래처럼 <!-- 와  --> 로 감싸서 말이죠. 

<style type="text/css">
<!--
body, td {
   color: blue;
}
-->
</style>

CSS Comments ( 주석 )

CSS에서 주석은 /* 주석처리 할 내용 */  이렇게 쓰시면 됩니다. 여러 줄에 걸쳐도 관계 없습니다. 

예제:

/* This is an external style sheet file */
h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
/* end of 
style rules. */

 

 

 

 

 

 

Reference : http://www.tutorialspoint.com/css/css_inclusion.htm

 

 

 

 

 

 

'💻 Programming > CSS' 카테고리의 다른 글

[CSS] 6. Background ( 배경 설정 )  (0) 2016.06.12
[CSS] 5. Colors ( 색깔 )  (0) 2016.06.12
[CSS] 4. Units ( 단위 )  (0) 2016.06.12
[CSS] 2. Syntax ( 문법, 사용법 )  (0) 2016.06.12
[CSS] 1. CSS란 ?  (0) 2016.06.11

💻 Programming/CSS

[CSS] 2. Syntax ( 문법, 사용법 )

 

CSS 를 사용하려면 문법에 따라야겠죠?? 이번 포스팅에서는 그 문법에 대해서 알아보도록 하겠습니다.  

CSS는 스타일 규칙을 따르는데 이 스타일 규칙에는 세가지 요소가 있습니다. 

  • 셀렉터 : 셀렉터는 HTML 태그의 이름을 말합니다. 예를들면 <h1> 태그의 h1이나 <table> 태그의 table이 셀렉터인거죠.

  • 속성 : 속성은 html태그 내에서 사용되는 그런 속성들을 말합니다. color나 border같은 것들을 말하는거죠.

  • 값 : 이 값은 속성에 할당되는 값을 말합니다. color속성이 red값을 갖는다 뭐 이런거죠.

이 세가지 요소를 합하면 그게바로 아래와 같은 스타일 규칙입니다.

셀렉터 { 속성 : 값 }

예제 : 테이블 셀렉터의 속성 지정하기

table{ border :1px solid #C00; }

위 예제가 뭐하는건지 이해가 되나요? table태그의 속성 중에 border 속성 값을 1px solid #C00 로 설정을 한겁니다.

 

자, 이제 어느정도 감이 오나요???  

 

그럼 이제 셀렉터들이 어떤 것들이 있는지도 한번 봐볼까요? 

The Type Selectors ( 타입 셀렉터 )

h1태그가 뭔지는 이미 아시겠죠? 레벨1 헤더 태그죠. 그 태그의 색깔 속성을 지정해주는 예제가 밑에 있군요.

h1 { 
   color: #36CFFF; 
}

The Universal Selectors ( 유니버설 셀렉터 )

하나의 특정한 셀렉터를 선택하는 것이 아니라 모든 셀렉터에 대해서 속성을 지정해주고 싶을때 사용하는 유니버설 셀렉터입니다. * 기호는 "모든"이라는 의미를 갖고있죠.

* { 
  color: #000000; 
}

모든 셀렉터(태그)에 대해서 색까 속성값을 검정으로 설정한 예제죠? 아닌가요? 

The Descendant Selectors ( 후손 셀렉터 )

태그안에 또 다른 태그가 들어갈 수가 있습니다. 그럴때 후손 셀렉터에 대해서만 적용을 하고 싶은 속성값이 있을텐데 그럴때는 아래와 같이 사용하시면 됩니다. 아래 예제는 ul태그 안에 사용된 em태그의 속성을 지정해주는 예제입니다.

ul em {
  color: #000000; 
}

The Class Selectors ( 클래스 셀렉터 )

만약 클래스 단위로 속성값을 지정해주고 싶다면 클래스 셀렉터를 사용하시면 됩니다.  

사용법은 아래와 같습니다. 점(.)을 찍고 붙여서 클래스명을 써주시면 됩니다. 

.black {
  color: #000000; 
}

위 예제는 black클래스에 속한 모든 태그의 색을 검정색(#000000)으로 지정해주는 예제네요 . 좀 더 범위를 좁혀서 아래처럼 사용하실 수도 있습니다.  

h1.black {
  color: #000000; 
}

 <h1> 태그이면서 black클래스에 속한 태그들의 색깔을 모두 #000000으로 지정해주는 예제군요.

 

# 참고로 아래처럼 하나의 태그에 여러개의 클래스를 부여할 수 있다는 점도 알고계시면 좋겠네요:

<p class="center bold">
This para will be styled by the classes center and bold.
</p>

The ID Selectors ( 아이디 셀렉터 )

이번에는 아이디 셀렉터에 대해서 보도록 하겠습니다. 모든 태그에는 아이디를 부여할 수 있습니다. 그리고 그렇게 부여된 아이디를 셀렉트하기위해서는 # 기호를 사용합니다. 

#black {
  color: #000000; 
}

위 예제는 id가 black인 요소의 색깔을 검정으로 지정하는 예제입니다.

h1#black {
  color: #000000; 
}

위 예제는 <h1> 요소내의 모든 요소들 중에서 id가 black인 녀석에게만 검정색 속성을 주었네요

이 id셀렉터가 가장 유용하게 쓰이는 경우는 아래처럼 후손 셀렉터들에게 속성을 부여할 때입니다.

#black h2 {
  color: #000000; 
}

위 예제는 태그id가 black인 태그내의 h2태그의 색깔 속성값을 지정해주는 예제죠? 아닌가요? 맞습니다. 

The Child Selectors ( 자식 셀렉터 )

위에서 말한 후손 셀렉터는 descendant 라고하여 모든 후손들에 대해 적용이 됩니다. 하지만 이 자식 셀렉터는 직계 자식만 해당이 됩니다. 예제를 한번 보실까요.

body > p {
  color: #000000; 
}

<body> 태그 바로 밑에 있는 <p> 에 대해서만 적용되는 스타일을 정의했군요. body안의 div안에서 사용된 p태그는 위 스타일의 적용을 받지 않습니다.

The Attribute Selectors ( 속성 셀렉터 )

아래 예제는 input태그의 type속성이 text인 녀석들의 색을 지정해주는 예제입니다.

input[type="text"]{
  color: #000000; 
}

위에 정의된 스타일은 <input type="submit" /> 요소에는 적용이 되지 않는다는 것이죠.

아래는 속성 셀렉터의 사용법입니다.

  • p[lang]lang 속성을 갖는 모든 문단요소를 선택.

  • p[lang="fr"] - lang attribute이 "fr"인 모든 문단 요소를 선택.

  • p[lang~="fr"] - lang 속성이 "fr"을 포함하는 모든 문단 요소를 선택.

  • p[lang|="en"] - lang 속성이 "en"이거나 또는 "en"으로 시작하는 문단 요소를 선택.

Multiple Style Rules ( 다중 스타일 규칙 )

지금까지는 하나의 요소에 하나의 스타일만 적용을 했습니다. 하지만 요소마다 여러개의 속성을 가질 수 있으니 여러개의 스타일을 지정할 수도 있어야겠죠?  

h1 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

위 예제처럼 세미콜론 (;) 으로 스타일을 구분하여 정의해주면 됩니다. 간단하죠?

각 속성에 지정된 속성값들에 대해서는 이게 뭔가 하실 수도 있는데 신경쓰지마시고 일단 넘어가세요. 차근차근 배우면 됩니다 ^___^ 

Grouping Selectors ( 셀렉터 그룹화 )

내가 지정한 스타일을 여러개의 요소에 한꺼번에!!!!  적용하고 싶으시다면!!!!

h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

위 예제는 h1, h2 and h3 요소에 한꺼번에 스타일을 적용시키는 예제입니다. 순서는 전혀 상관이 없구요 콤마를 이용해서 셀렉터들을 구분지어주시면 되겠습니다. 아래처럼 아이디 셀렉터를 이용할 수도 있습니다.

#content, #footer, #supplement {
position: absolute;
left: 510px;
width: 200px;
}

클래스 셀렉터나 다른 셀렉터들을 함께 사용해보는 연습도 해보세요 ^____^

 

 

 

 

Reference : http://www.tutorialspoint.com/css/css_syntax.htm

 

 

 

 

 

 

'💻 Programming > CSS' 카테고리의 다른 글

[CSS] 6. Background ( 배경 설정 )  (0) 2016.06.12
[CSS] 5. Colors ( 색깔 )  (0) 2016.06.12
[CSS] 4. Units ( 단위 )  (0) 2016.06.12
[CSS] 3. HTML에 CSS링크 - Associating Styles with HTML  (0) 2016.06.12
[CSS] 1. CSS란 ?  (0) 2016.06.11

💻 Programming/웹프로그래밍

[jQuery] 10. Effects ( 효과 )

jQuery provides a trivially simple interface for doing various kind of amazing effects. jQuery methods allow us to quickly apply commonly used effects with a minimum configuration.

This tutorial covers all the important jQuery methods to create visual effects.


요소 숨기기와 보이기

The commands for showing and hiding elements are pretty much what we would expect: show() to show the elements in a wrapped set and hide() to hide them.

문법:

Here is the simple syntax for show() method:

[selector].show( speed, [callback] );

Here is the description of all the parameters:

  • speed: A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).

  • callback: This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.

Following is the simple syntax for hide() method:

[selector].hide( speed, [callback] );

Here is the description of all the parameters:

  • speed: A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).

  • callback: This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.

예제:

Consider the following HTML file with a small JQuery coding:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {

     $("#show").click(function () {
        $(".mydiv").show( 1000 );
     });

     $("#hide").click(function () {
        $(".mydiv").hide( 1000 );
     });

   });

   </script>
   <style>
   .mydiv{ margin:10px;padding:12px;
      border:2px solid #666;
      width:100px;
      height:100px;
    }
  </style>
</head>
<body>
   <div class="mydiv">
      This is  SQUAR
   </div>

   <input id="hide" type="button" value="Hide" />   
   <input id="show" type="button" value="Show" />   

</body>
</html>

 

 

요소 토글링

jQuery provides methods to toggle the display state of elements between revealed or hidden. If the element is initially displayed, it will be hidden; if hidden, it will be shown.

문법:

Here is the simple syntax for one of the toggle() methods:

[selector]..toggle([speed][, callback]);

Here is the description of all the parameters:

  • speed: A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).

  • callback: This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.

예제:

We can animate any element, such as a simple <div> containing an image:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $(".clickme").click(function(event){
          $(".target").toggle('slow', function(){
             $(".log").text('Transition Complete');
          });
      });

   });
   </script>
   <style>
   .clickme{ margin:10px;padding:12px;
      border:2px solid #666;
      width:100px;
      height:50px;
    }
   </style>
</head>
<body>
   <div class="content">
      <div class="clickme">Click Me</div>
      <div class="target">
         <img src="/images/jquery.jpg" alt="jQuery" />
      </div>
      <div class="log"></div>
</body>
</html>

 

 

JQuery 효과 관련 메소드 목록

 

Methods and Description
animate( params, [duration, easing, callback] )
A function for making custom animations.
fadeIn( speed, [callback] )
Fade in all matched elements by adjusting their opacity and firing an optional callback after completion.
fadeOut( speed, [callback] )
Fade out all matched elements by adjusting their opacity to 0, then setting display to "none" and firing an optional callback after completion.
fadeTo( speed, opacity, callback )
Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion.
hide( )
Hides each of the set of matched elements if they are shown.
hide( speed, [callback] )
Hide all matched elements using a graceful animation and firing an optional callback after completion.
show( )
Displays each of the set of matched elements if they are hidden.
show( speed, [callback] )
Show all matched elements using a graceful animation and firing an optional callback after completion.
slideDown( speed, [callback] )
Reveal all matched elements by adjusting their height and firing an optional callback after completion.
slideToggle( speed, [callback] )
Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion.
slideUp( speed, [callback] )
Hide all matched elements by adjusting their height and firing an optional callback after completion.
stop( [clearQueue, gotoEnd ])
Stops all the currently running animations on all the specified elements.
toggle( )
Toggle displaying each of the set of matched elements.
toggle( speed, [callback] )
Toggle displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion.
toggle( switch )
Toggle displaying each of the set of matched elements based upon the switch (true shows all elements, false hides all elements).
jQuery.fx.off
Globally disable all animations.


UI 라이브러리에서 제공하는 효과 목록

To use these effects you would have to download jQuery UI Library jquery-ui-1.7.2.custom.min.js or latest version of this UI library from jQuery UI Library.

After extracting jquery-ui-1.7.2.custom.min.js file from the download, you would include this file in similar way as you include core jQuery Library file.

Methods and Description
Blind
Blinds the element away or shows it by blinding it in.
Bounce
Bounces the element vertically or horizontally n-times.
Clip
Clips the element on or off, vertically or horizontally.
Drop
Drops the element away or shows it by dropping it in.
Explode
Explodes the element into multiple pieces.
Fold
Folds the element like a piece of paper.
Highlight
Highlights the background with a defined color.
Puff
Scale and fade out animations create the puff effect.
Pulsate
Pulsates the opacity of the element multiple times.
Scale
Shrink or grow an element by a percentage factor.
Shake
Shakes the element vertically or horizontally n-times.
Size
Resize an element to a specified width and height.
Slide
Slides the element out of the viewport.
Transfer
Transfers the outline of an element to another.

 

 

 

 

Reference : http://www.tutorialspoint.com/jquery/jquery-effects.htm 

 

 

 

 

💻 Programming/웹프로그래밍

[jQuery] 9. AJAX

AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology help us to load data from the server without a browser page refresh.

If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.

JQuery is a great tool which provides a rich set of AJAX methods to develope next generation web application.


데이타 로딩하기

This is very easy to load any static or dynamic data using JQuery AJAX. JQuery provides load() method to do the job:

문법:

Here is the simple syntax for load() method:

[selector].load( URL, [data], [callback] );

Here is the description of all the parameters:

  • URL: The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database.

  • data: This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used.

  • callback: A callback function invoked after the response data has been loaded into the elements of the matched set. The first parameter passed to this function is the response text recieved from the server and second parameter is the status code.

예제:

Consider the following HTML file with a small JQuery coding:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   $(document).ready(function() {
      $("#driver").click(function(event){
          $('#stage').load('/jquery/result.html');
      });
   });
   </script>
</head>
<body>
   <p>Click on the button to load result.html file:</p>
   <div id="stage" style="background-color:blue;">
          STAGE
   </div>
   <input type="button" id="driver" value="Load Data" />
</body>
</html>

Here load() initiates an Ajax request to the specified URL /jquery/result.html file. After loading this file, all the content would be populated inside <div> tagged with ID stage. Assuming, our /jquery/result.html file has just one HTML line:

   <h1>THIS IS RESULT...</h1>

When you click the given button, then result.html file gets loaded. 


JSON 데이타 읽어오기

There would be a situation when server would return JSON string against your request. JQuery utility function getJSON() parses the returned JSON string and makes the resulting string available to the callback function as first parameter to take further action.

문법:

Here is the simple syntax for getJSON() method:

[selector].getJSON( URL, [data], [callback] );

Here is the description of all the parameters:

  • URL: The URL of the server-side resource contacted via the GET method.

  • data: An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string.

  • callback: A function invoked when the request completes. The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second.

예제:

Consider the following HTML file with a small JQuery coding:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   $(document).ready(function() {
      $("#driver").click(function(event){
          $.getJSON('/jquery/result.json', function(jd) {
             $('#stage').html('<p> Name: ' + jd.name + '</p>');
             $('#stage').append('<p>Age : ' + jd.age+ '</p>');
             $('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
          });
      });
   });
   </script>
</head>
<body>
   <p>Click on the button to load result.html file:</p>
   <div id="stage" style="background-color:blue;">
          STAGE
   </div>
   <input type="button" id="driver" value="Load Data" />
</body>
</html>

Here JQuery utility method getJSON() initiates an Ajax request to the specified URL /jquery/result.json file. After loading this file, all the content would be passed to the callback function which finally would be populated inside <div> tagged with ID stage. Assuming, our /jquery/result.json file has following json formatted content:

{
"name": "Zara Ali",
"age" : "67",
"sex": "female"
}

When you click the given button, then result.json file gets loaded.


서버로 데이타 전달하기

Many times you collect input from the user and you pass that input to the server for further processing. JQuery AJAX made it easy enough to pass collected data to the server using data parameter of any available Ajax method.

예제:

This example demonstrate how can pass user input to a web server script which would send the same result back and we would print it:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   $(document).ready(function() {
      $("#driver").click(function(event){
          var name = $("#name").val();
          $("#stage").load('/jquery/result.php', {"name":name} );
      });
   });
   </script>
</head>
<body>
   <p>Enter your name and click on the button:</p>
   <input type="input" id="name" size="40" /><br />
   <div id="stage" style="background-color:blue;">
          STAGE
   </div>
   <input type="button" id="driver" value="Show Result" />
</body>
</html>

Here is the code written in result.php script:

<?php
if( $_REQUEST["name"] )
{
   $name = $_REQUEST['name'];
   echo "Welcome ". $name;
}
?> 

Now you can enter any text in the given input box and then click "Show Result" button to see what you have entered in the input box. 


JQuery에서 사용되는 AJAX 메소드 목록

 

Methods and Description
jQuery.ajax( options )
Load a remote page using an HTTP request.
jQuery.ajaxSetup( options )
Setup global settings for AJAX requests.
jQuery.get( url, [data], [callback], [type] )
Load a remote page using an HTTP GET request.
jQuery.getJSON( url, [data], [callback] )
Load JSON data using an HTTP GET request.
jQuery.getScript( url, [callback] )
Loads and executes a JavaScript file using an HTTP GET request.
jQuery.post( url, [data], [callback], [type] )
Load a remote page using an HTTP POST request.
load( url, [data], [callback] )
Load HTML from a remote file and inject it into the DOM.
serialize( )
Serializes a set of input elements into a string of data.
serializeArray( )
Serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with.


JQuery AJAX 이벤트 목록


Methods and Description
ajaxComplete( callback )
Attach a function to be executed whenever an AJAX request completes.
ajaxStart( callback )
Attach a function to be executed whenever an AJAX request begins and there is none already active.
ajaxError( callback )
Attach a function to be executed whenever an AJAX request fails.
ajaxSend( callback )
Attach a function to be executed before an AJAX request is sent.
ajaxStop( callback )
Attach a function to be executed whenever all AJAX requests have ended.
ajaxSuccess( callback )
Attach a function to be executed whenever an AJAX request completes successfully.

 

 

 

 

Reference : http://www.tutorialspoint.com/jquery/jquery-ajax.htm

 

 

 

 

We have the ability to create dynamic web pages by using events. Events are actions that can be detected by your Web Application.

Following are the examples events:

  • A mouse click
  • A web page loading
  • Taking mouse over an element
  • Submitting an HTML form
  • A keystroke on your keyboard
  • etc.

When these events are triggered you can then use a custom function to do pretty much whatever you want with the event. These custom functions call Event Handlers.


이벤트 핸들러 바인딩하기

Using the jQuery Event Model, we can establish event handlers on DOM elements with the bind() method as follows:

$('div').bind('click', function( event ){
   alert('Hi there!');
});

This code will cause the division element to respond to the click event; when a user clicks inside this division thereafter, the alert will be shown.

The full syntax of the bind() command is as follows:

selector.bind( eventType[, eventData], handler)

Following is the description of the parameters:

  • eventType: A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.

  • eventData: This is optional parameter is a map of data that will be passed to the event handler.

  • handler: A function to execute each time the event is triggered.


이벤트 핸들러 삭제하기

Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler.

jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows:

selector.unbind(eventType, handler)

or 

selector.unbind(eventType)

Following is the description of the parameters:

  • eventType: A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.

  • handler: If provided, identifies the specific listener that has to be removed.


이벤트 타입

The following are cross platform and recommended event types which you can bind using JQuery:

Event TypeDescription
blurOccurs when the element loses focus
changeOccurs when the element changes
clickOccurs when a mouse click
dblclickOccurs when a mouse double-click
errorOccurs when there is an error in loading or unloading etc.
focusOccurs when the element gets focus
keydownOccurs when key is pressed
keypressOccurs when key is pressed and released
keyupOccurs when key is released
loadOccurs when document is loaded
mousedownOccurs when mouse button is pressed
mouseenterOccurs when mouse enters in an element region
mouseleaveOccurs when mouse leaves an element region
mousemoveOccurs when mouse pointer moves
mouseoutOccurs when mouse pointer moves out of an element
mouseoverOccurs when mouse pointer moves over an element
mouseupOccurs when mouse button is released
resizeOccurs when window is resized
scrollOccurs when window is scrolled
selectOccurs when a text is selected
submitOccurs when form is submitted
unloadOccurs when documents is unloaded


이벤트 객체

The callback function takes a single parameter; when the handler is called the JavaScript event object will be passed through it.

The event object is often unneccessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered, however there are certail attributes which you would need to be accessed.

이벤트 속성

The following event properties/attributes are available and safe to access in a platform independent manner:

PropertyDescription
altKeySet to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards.
ctrlKeySet to true if the Ctrl key was pressed when the event was triggered, false if not.
dataThe value, if any, passed as the second parameter to the bind() command when the handler was established.
keyCodeFor keyup and keydown events, this returns the key that was pressed.
metaKeySet to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the Ctrl key on PCs and the Command key on Macs.
pageXFor mouse events, specifies the horizontal coordinate of the event relative from the page origin.
pageYFor mouse events, specifies the vertical coordinate of the event relative from the page origin.
relatedTargetFor some mouse events, identifies the element that the cursor left or entered when the event was triggered.
screenXFor mouse events, specifies the horizontal coordinate of the event relative from the screen origin.
screenYFor mouse events, specifies the vertical coordinate of the event relative from the screen origin.
shiftKeySet to true if the Shift key was pressed when the event was triggered, false if not.
targetIdentifies the element for which the event was triggered.
timeStampThe timestamp (in milliseconds) when the event was created.
typeFor all events, specifies the type of event that was triggered (for example, click).
whichFor keyboard events, specifies the numeric code for the key that caused the event, and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3 for right)

 

 

이벤트 객체의 메소드

There is a list of methods which can be called on an Event Object:

MethodDescription
preventDefault()Prevents the browser from executing the default action.
isDefaultPrevented()Returns whether event.preventDefault() was ever called on this event object.
stopPropagation() Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.
isPropagationStopped() Returns whether event.stopPropagation() was ever called on this event object.
stopImmediatePropagation() Stops the rest of the handlers from being executed.
isImmediatePropagationStopped()Returns whether event.stopImmediatePropagation() was ever called on this event object.


이벤트 조작 관련 메소드

Following table lists down important event-related methods:

MethodDescription
bind( type, [data], fn )Binds a handler to one or more events (like click) for each matched element. Can also bind custom events.
die( type, fn )This does the opposite of live, it removes a bound live event.
hover( over, out )Simulates hovering for example moving the mouse on, and off, an object.
live( type, fn )Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
one( type, [data], fn )Binds a handler to one or more events to be executed once for each matched element.
ready( fn )Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.
toggle( fn, fn2, fn3,... )Toggle among two or more function calls every other click.
trigger( event, [data] )Trigger an event on every matched element.
triggerHandler( event, [data] )Triggers all bound event handlers on an element .
unbind( [type], [fn] )This does the opposite of bind, it removes bound events from each of the matched elements.


이벤트 핸들러 메소드

jQuery also provides a set of event helper functions which can be used either to trigger an event to bind any event types mentioned above.

트리거 메소드

Following is an example which would triggers the blur event on all paragraphs:

$("p").blur();

바인딩 메소드

Following is an example which would bind a click event on all the <div>:

$("div").click( function () { 
   // do something here
});

 

 

Here is a complete list of all the support methods provided by jQuery:

MethodDescription
blur( )Triggers the blur event of each matched element.
blur( fn )Bind a function to the blur event of each matched element.
change( )Triggers the change event of each matched element.
change( fn )Binds a function to the change event of each matched element.
click( )Triggers the click event of each matched element.
click( fn )Binds a function to the click event of each matched element.
dblclick( )Triggers the dblclick event of each matched element.
dblclick( fn )Binds a function to the dblclick event of each matched element.
error( )Triggers the error event of each matched element.
error( fn )Binds a function to the error event of each matched element.
focus( )Triggers the focus event of each matched element.
focus( fn )Binds a function to the focus event of each matched element.
keydown( )Triggers the keydown event of each matched element.
keydown( fn )Bind a function to the keydown event of each matched element.
keypress( )Triggers the keypress event of each matched element.
keypress( fn )Binds a function to the keypress event of each matched element.
keyup( )Triggers the keyup event of each matched element.
keyup( fn )Bind a function to the keyup event of each matched element.
load( fn )Binds a function to the load event of each matched element.
mousedown( fn )Binds a function to the mousedown event of each matched element.
mouseenter( fn )Bind a function to the mouseenter event of each matched element.
mouseleave( fn )Bind a function to the mouseleave event of each matched element.
mousemove( fn )Bind a function to the mousemove event of each matched element.
mouseout( fn )Bind a function to the mouseout event of each matched element.
mouseover( fn )Bind a function to the mouseover event of each matched element.
mouseup( fn )Bind a function to the mouseup event of each matched element.
resize( fn )Bind a function to the resize event of each matched element.
scroll( fn )Bind a function to the scroll event of each matched element.
select( )Trigger the select event of each matched element.
select( fn )Bind a function to the select event of each matched element.
submit( )Trigger the submit event of each matched element.
submit( fn )Bind a function to the submit event of each matched element.
unload( fn )Binds a function to the unload event of each matched element.

 

 

 

 

 

 Reference : http://www.tutorialspoint.com/jquery/jquery-events.htm

 

 

 

 

 

JQuery provides methods to manipulate DOM in efficient way. You do not need to write big code to modify the value of any element's attribute or to extract HTML code from a paragraph or division.

JQuery provides methods such as .attr(), .html(), and .val() which act as getters, retrieving information from DOM elements for later use.

컨텐츠 조작:

The html( ) method gets the html contents (innerHTML) of the first matched element.

Here is the syntax for the method:

selector.html( )

예제:

Following is an example which makes use of .html() and .text(val) methods. Here .html() retrieves HTML content from the object and then .text( val ) method sets value of the object using passed parameter:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {

     $("div").click(function () {
      var content = $(this).html();
      $("#result").text( content );
    });

   });

   </script>
   <style>
      #division{ margin:10px;padding:12px;
                 border:2px solid #666;
                 width:60px;
               }
  </style>
</head>
<body>
   <p>Click on the square below:</p>
   <span id="result"> </span>
   <div id="division" style="background-color:blue;">
     This is Blue Square!!
   </div>
</body>
</html>

 

 

DOM 요소 변경

You can replace a complete DOM element with the specified HTML or DOM elements. The replaceWith( content ) method serves this purpose very well.

Here is the syntax for the method:

selector.replaceWith( content )

Here content is what you want to have instead of original element. This could be HTML or simple text.

예제:

Following is an example which would replace division element with "<h1>JQuery is Great</h1>":

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {

     $("div").click(function () {
       $(this).replaceWith("<h1>JQuery is Great</h1>");
    });

   });

   </script>
   <style>
      #division{ margin:10px;padding:12px;
                 border:2px solid #666;
                 width:60px;
               }
  </style>
</head>
<body>
   <p>Click on the square below:</p>
   <span id="result"> </span>
   <div id="division" style="background-color:blue;">
     This is Blue Square!!
   </div>
</body>
</html>

 

 

DOM 요소 삭제

There may be a situation when you would like to remove one or more DOM elements from the document. JQuery provides two methods to handle the situation.

The empty( ) method remove all child nodes from the set of matched elements where as the method remove( expr ) method removes all matched elements from the DOM.

Here is the syntax for the method:

selector.remove( [ expr ])

or 

selector.empty( )

You can pass optional paramter expr to filter the set of elements to be removed.

예제:

Following is an example where elements are being removed as soon as they are clicked:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {

     $("div").click(function () {
       $(this).remove( );
    });

   });

   </script>
   <style>
      .div{ margin:10px;padding:12px;
             border:2px solid #666;
             width:60px;
           }
  </style>
</head>
<body>
   <p>Click on any square below:</p>
   <span id="result"> </span>
   <div class="div" style="background-color:blue;"></div>
   <div class="div" style="background-color:green;"></div>
   <div class="div" style="background-color:red;"></div>
</body>
</html>

 

 

DOM 요소 추가

There may be a situation when you would like to insert new one or more DOM elements in your existing document. JQuery provides various methods to insert elements at various locations.

The after( content ) method insert content after each of the matched elements where as the method before( content ) method inserts content before each of the matched elements.

Here is the syntax for the method:

selector.after( content )

or

selector.before( content )

Here content is what you want to insert. This could be HTML or simple text.

예제:

Following is an example where <div> elements are being inserted just before the clicked element:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {

     $("div").click(function () {
       $(this).before('<div class="div"></div>' );
    });

   });

   </script>
   <style>
      .div{ margin:10px;padding:12px;
             border:2px solid #666;
             width:60px;
           }
  </style>
</head>
<body>
   <p>Click on any square below:</p>
   <span id="result"> </span>
   <div class="div" style="background-color:blue;"></div>
   <div class="div" style="background-color:green;"></div>
   <div class="div" style="background-color:red;"></div>
</body>
</html>

 

 

DOM 조작 관련 메소드 목록

 

MethodDescription
after( content )Insert content after each of the matched elements.
append( content )Append content to the inside of every matched element.
appendTo( selector )Append all of the matched elements to another, specified, set of elements.
before( content )Insert content before each of the matched elements.
clone( bool )Clone matched DOM Elements, and all their event handlers, and select the clones.
clone( )Clone matched DOM Elements and select the clones.
empty( )Remove all child nodes from the set of matched elements.
html( val )Set the html contents of every matched element.
html( )Get the html contents (innerHTML) of the first matched element.
insertAfter( selector )Insert all of the matched elements after another, specified, set of elements.
insertBefore( selector )Insert all of the matched elements before another, specified, set of elements.
prepend( content )Prepend content to the inside of every matched element.
prependTo( selector )Prepend all of the matched elements to another, specified, set of elements.
remove( expr )Removes all matched elements from the DOM.
replaceAll( selector )Replaces the elements matched by the specified selector with the matched elements.
replaceWith( content )Replaces all matched elements with the specified HTML or DOM elements.
text( val )Set the text contents of all matched elements.
text( )Get the combined text contents of all matched elements.
wrap( elem )Wrap each matched element with the specified element.
wrap( html )Wrap each matched element with the specified HTML content.
wrapAll( elem )Wrap all the elements in the matched set into a single wrapper element.
wrapAll( html )Wrap all the elements in the matched set into a single wrapper element.
wrapInner( elem )Wrap the inner child contents of each matched element (including text nodes) with a DOM element.
wrapInner( html )Wrap the inner child contents of each matched element (including text nodes) with an HTML structure.

 

 

 

 

Reference : http://www.tutorialspoint.com/jquery/jquery-dom.htm

 

 

 

 

💻 Programming/웹프로그래밍

[jQuery] 6. CSS Methods ( CSS 메소드 )

 

The jQuery library supports nearly all of the selectors included in Cascading Style Sheet (CSS) specifications 1 through 3, as outlined on the World Wide Web Consortium's site.

Using JQuery library developers can enhance their websites without worrying about browsers and their versions as long as the browsers have JavaScript enabled.

Most of the JQuery CSS Methods do not modify the content of the jQuery object and they are used to apply CSS properties on DOM elements.


CSS 속성 적용하기

This is very simple to apply any CSS property using JQuery method css( PropertyName, PropertyValue ).

Here is the syntax for the method:

selector.css( PropertyName, PropertyValue );

Here you can pass PropertyName as a javascript string and based on its value, PropertyValue could be string or integer.

예제:

Following is an example which adds font color to the second list item.

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {
      $("li").eq(2).css("color", "red");
   });

   </script>
</head>
<body>
   <div>
   <ul>
     <li>list item 1</li>
     <li>list item 2</li>
     <li>list item 3</li>
     <li>list item 4</li>
     <li>list item 5</li>
     <li>list item 6</li>
   </ul>
   </div>
</body>
</html>

 

 

CSS 속성 다중 적용하기

You can apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call.

Here is the syntax for the method:

selector.css( {key1:val1, key2:val2....keyN:valN})

Here you can pass key as property and val as its value as described above.

예제:

Following is an example which adds font color as well as background color to the second list item.

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {
      $("li").eq(2).css({"color":"red", 
                         "background-color":"green"});
   });

   </script>
</head>
<body>
   <div>
   <ul>
     <li>list item 1</li>
     <li>list item 2</li>
     <li>list item 3</li>
     <li>list item 4</li>
     <li>list item 5</li>
     <li>list item 6</li>
   </ul>
   </div>
</body>
</html>

 

 

요소의 Width & Height 세팅하기

The width( val ) and height( val ) method can be used to set the width and hieght respectively of any element.

예제:

Following is a simple example which sets the width of first division element where as rest of the elements have width set by style sheet:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {
      $("div:first").width(100);
      $("div:first").css("background-color", "blue");
   });

   </script>
   <style>
   div{ width:70px; height:50px; float:left; margin:5px;
      background:red; cursor:pointer; }
  </style>
</head>
<body>
  <div></div>
  <div>d</div>
  <div>d</div>
  <div>d</div>
  <div>d</div>
</body>
</html>

 

 

JQuery CSS 메소드

다음은 CSS 속성과 관련있는 모든 메소드 목록입니다. 

MethodDescription
css( name )Return a style property on the first matched element.
css( name, value )Set a single style property to a value on all matched elements.
css( properties )Set a key/value object as style properties to all matched elements.
height( val )Set the CSS height of every matched element.
height( )Get the current computed, pixel, height of the first matched element.
innerHeight( )Gets the inner height (excludes the border and includes the padding) for the first matched element.
innerWidth( )Gets the inner width (excludes the border and includes the padding) for the first matched element.
offset( )Get the current offset of the first matched element, in pixels, relative to the document
offsetParent( )Returns a jQuery collection with the positioned parent of the first matched element.
outerHeight( [margin] )Gets the outer height (includes the border and padding by default) for the first matched element.
outerWidth( [margin] )Get the outer width (includes the border and padding by default) for the first matched element.
position( )Gets the top and left position of an element relative to its offset parent.
scrollLeft( val )When a value is passed in, the scroll left offset is set to that value on all matched elements.
scrollLeft( )Gets the scroll left offset of the first matched element.
scrollTop( val )When a value is passed in, the scroll top offset is set to that value on all matched elements.
scrollTop( )Gets the scroll top offset of the first matched element.
width( val )Set the CSS width of every matched element.
width( )Get the current computed, pixel, width of the first matched element.

 

 

 

 

  

Reference : http://www.tutorialspoint.com/jquery/jquery-css.htm

 

 

 

 

💻 Programming/웹프로그래밍

[jQuery] 5. DOM Traversing ( DOM 선회 )

jQuery is a very powerful tool which provides a variety of DOM traversal methods to help us select elements in a document randomly as well as in sequential method.

Most of the DOM Traversal Methods do not modify the jQuery object and they are used to filter out elements from a document based on given conditions.


인덱스를 이용한 돔 요소 찾기

Consider a simple document with the following HTML content:

<html>
<head>
<title>the title</title>
</head>
<body>
   <div>
   <ul>
     <li>list item 1</li>
     <li>list item 2</li>
     <li>list item 3</li>
     <li>list item 4</li>
     <li>list item 5</li>
     <li>list item 6</li>
   </ul>
   </div>
</body>
</html>
  • Above every list has its own index, and can be located directly by using eq(index) method as below example.

  • Every child element starts its index from zero, thus, list item 2 would be accessed by using $("li").eq(1) and so on.

예제:

Following is a simple example which adds the color to second list item.

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {
      $("li").eq(2).addClass("selected");
   });

   </script>
   <style>
      .selected { color:red; }
  </style>
</head>
<body>
   <div>
   <ul>
     <li>list item 1</li>
     <li>list item 2</li>
     <li>list item 3</li>
     <li>list item 4</li>
     <li>list item 5</li>
     <li>list item 6</li>
   </ul>
   </div>
</body>
</html>

 

 

요소 필터링하기

The filter( selector ) method can be used to filter out all elements from the set of matched elements that do not match the specified selector(s). The selector can be written using any selector syntax.

예제:

Following is a simple example which applies color to the lists associated with middle class:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {
      $("li").filter(".middle").addClass("selected");
   });

   </script>
   <style>
      .selected { color:red; }
  </style>
</head>
<body>
   <div>
   <ul>
     <li class="top">list item 1</li>
     <li class="top">list item 2</li>
     <li class="middle">list item 3</li>
     <li class="middle">list item 4</li>
     <li class="bottom">list item 5</li>
     <li class="bottom">list item 6</li>
   </ul>
   </div>
</body>
</html>

 

 

내부 요소 찾기

The find( selector ) method can be used to locate all the descendent elements of a particular type of elements. The selector can be written using any selector syntax.

예제:

Following is an example which selects all the <span> elements available inside different <p> elements:

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $("p").find("span").addClass("selected");
   });

   </script>
   <style>
      .selected { color:red; }
  </style>
</head>
<body>
   <p>This is 1st paragraph and <span>THIS IS RED</span></p>
   <p>This is 2nd paragraph and <span>THIS IS ALSO RED</span></p>
</body>
</html>

 

 

유용한 JQuery DOM Traversing 메소드

 Following table lists down useful methods which you can use to filter out various elements from a list of DOM elements:

SelectorDescription
eq( index )Reduce the set of matched elements to a single element.
filter( selector )Removes all elements from the set of matched elements that do not match the specified selector(s).
filter( fn )Removes all elements from the set of matched elements that do not match the specified function.
is( selector )Checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector.
map( callback )Translate a set of elements in the jQuery object into another set of values in a jQuery array (which may, or may not contain elements).
not( selector )Removes elements matching the specified selector from the set of matched elements.
slice( start, [end] )Selects a subset of the matched elements.

 

 

 

Following table lists down other useful methods which you can use to locate various elements in a DOM:

SelectorDescription
add( selector )Adds more elements, matched by the given selector, to the set of matched elements.
andSelf( )Add the previous selection to the current selection.
children( [selector])Get a set of elements containing all of the unique immediate children of each of the matched set of elements.
closest( selector )Get a set of elements containing the closest parent element that matches the specified selector, the starting element included.
contents( )Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.
end( )Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state .
find( selector )Searches for descendent elements that match the specified selectors.
next( [selector] )Get a set of elements containing the unique next siblings of each of the given set of elements.
nextAll( [selector] )Find all sibling elements after the current element.
offsetParent( )Returns a jQuery collection with the positioned parent of the first matched element.
parent( [selector] )Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements.
parents( [selector] )Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element).
prev( [selector] )Get a set of elements containing the unique previous siblings of each of the matched set of elements.
prevAll( [selector] )Find all sibling elements in front of the current element.
siblings( [selector] )Get a set of elements containing all of the unique siblings of each of the matched set of elements.

 

 

 

 

 

Reference : http://www.tutorialspoint.com/jquery/jquery-traversing.htm

 

 

 

 

💻 Programming/웹프로그래밍

[jQuery] 4. DOM Attributes ( DOM 속성 )

 

Some of the most basic components we can manipulate when it comes to DOM elements are the properties and attributes assigned to those elements.

Most of these attributes are available through JavaScript as DOM node properties. Some of the more common properties are:

  • className

  • tagName

  • id

  • href

  • title

  • rel

  • src

Consider the following HTML markup for an image element:

<img id="myImage" src="image.gif" alt="An image" 
class="someClass" title="This is an image"/>

In this element's markup, the tag name is img, and the markup for id, src, alt, class, and title represents the element's attributes, each of which consists of a name and a value.

jQuery gives us the means to easily manipulate an element's attributes and gives us access to the element so that we can also change its properties.


속성값 읽어오기

속성값은 attr(name) 메소드를 이용하여 읽어올 수 있습니다.

예제:

아래 예제는 em요소의 title속성에 지정된 값을 읽어와서 div요소에 출력하는 예제네요.

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      var title = $("em").attr("title");
      $("#divid").text(title);
   });

   </script>
</head>
<body>
   <div>
      <em title="Bold and Brave">This is first paragraph.</em>
      <p id="myid">This is second paragraph.</p>
      <div id="divid"></div>
   </div>
</body>
</html>

 

 

속성값 수정하기

 attr(name, value) 메소드를 이용하여 특정 속성명에 대한 속성값을 설정해줄 수 있습니다.

예제:

아래 예제는 src 속성에 특정 파일경로를 설정해주는 예제입니다.

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $("#myimg").attr("src", "/images/jquery.jpg");
   });

   </script>
</head>
<body>
   <div>
      <img id="myimg" src="/wongpath.jpg" alt="Sample image" />
   </div>
</body>
</html>

 

 

스타일 적용하기

 addClass( classes ) 메소드를 이용하여 정의한 스타일을 적용시킬 수 있습니다.  여러개의 클래스를 스페이스를 구분자로 지정해줄 수 있습니다.

예제:

아래 예제는 문서내의 모든 em요소에 selected스타일을 적용시키고, id가 myid인 요소에는 highlight스타일을 적용시키는 예제입니다.
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $("em").addClass("selected");
      $("#myid").addClass("highlight");
   });

   </script>
   <style>
      .selected { color:red; }
      .highlight { background:yellow; }
  </style>
</head>
<body>
   <em title="Bold and Brave">This is first paragraph.</em>
   <p id="myid">This is second paragraph.</p>
</body>
</html>

 

 

유용한 속성 관련 메소드 목록

 

MethodsDescription
attr( properties )Set a key/value object as properties to all matched elements.
attr( key, fn )Set a single property to a computed value, on all matched elements.
removeAttr( name )Remove an attribute from each of the matched elements.
hasClass( class )Returns true if the specified class is present on at least one of the set of matched elements.
removeClass( class )Removes all or the specified class(es) from the set of matched elements.
toggleClass( class )Adds the specified class if it is not present, removes the specified class if it is present.
html( )Get the html contents (innerHTML) of the first matched element.
html( val )Set the html contents of every matched element.
text( )Get the combined text contents of all matched elements.
text( val )Set the text contents of all matched elements.
val( )Get the input value of the first matched element.
val( val )Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked.

Similar to above syntax and examples, following examples would give you understanding on using various attribute methods in different situation:

  • $("#myID").attr("custom") : This would return value of attribute custom for the first element matching with ID myID.

  • $("img").attr("alt", "Sample Image"): This sets the alt attribute of all the images to a new value "Sample Image".

  • $("input").attr({ value: "", title: "Please enter a value" }); : Sets the value of all <input> elements to the empty string, as well as sets the title to the string Please enter a value.

  • $("a[href^=http://]").attr("target","_blank"): Selects all links with an href attribute starting with http:// and set its target attribute to _blank

  • $("a").removeAttr("target") : This would remove target attribute of all the links.

  • $("form").submit(function() {$(":submit",this).attr("disabled", "disabled");}); : This would modify the disabled attribute to the value "disabled" while clicking Submit button.

  • $("p:last").hasClass("selected"): This return true if last <p> tag has associated classselected.

  • $("p").text(): Returns string that contains the combined text contents of all matched <p> elements.

  • $("p").text("<i>Hello World</i>"): This would set "<I>Hello World</I>" as text content of the matching <p> elements

  • $("p").html() : This returns the HTML content of the all matching paragraphs.

  • $("div").html("Hello World") : This would set the HTML content of all matching <div> to Hello World.

  • $("input:checkbox:checked").val() : Get the first value from a checked checkbox

  • $("input:radio[name=bar]:checked").val(): Get the first value from a set of radio buttons

  • $("button").val("Hello") : Sets the value attribute of every matched element <button>.

  • $("input").val("on") : This would check all the radio or check box button whose value is "on".

  • $("select").val("Orange") : This would select Orange option in a dropdown box with options Orange, Mango and Banana.

  • $("select").val("Orange", "Mango") : This would select Orange and Mango options in a dropdown box with options Orange, Mango and Banana.

 

 

 

 

Reference : http://www.tutorialspoint.com/jquery/jquery-attributes.htm 

 

 

 

 

 

 

💻 Programming/웹프로그래밍

[jQuery] 3. Selectors ( 셀렉터 )

 

 

The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM).

A jQuery Selector is a function which makes use of expressions to find out matching elements from a DOM based on the given criteria.

$() factory function (팩토리 함수):

All type of selectors available in jQuery, always start with the dollar sign and parentheses: $().

The factory function $() makes use of following three building blocks while selecting elements in a given document:

jQueryDescription
Tag Name:Represents a tag name available in the DOM. For example $('p') selects all paragraphs in the document.
Tag ID:Represents a tag available with the given ID in the DOM. For example $('#some-id') selects the single element in the document that has an ID of some-id.
Tag Class:Represents a tag available with the given class in the DOM. For example $('.some-class') selects all elements in the document that have a class of some-class.

All the above items can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking.

NOTE: The factory function $() is a synonym of jQuery() function. So in case you are using any other JavaScript library where $ sign is conflicting with some thing else then you can replace $ sign by jQuery name and you can use function jQuery() instead of $().

Example(예제):

Following is a simple example which makes use of Tag Selector. This would select all the elements with a tag name p.

<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   
   <script type="text/javascript" language="javascript">
   $(document).ready(function() {
      var pars = $("p");
      for( i=0; i<pars.length; i++ ){
         alert("Found paragraph: " + pars[i].innerHTML);
      }
   });
   </script>
</head>
<body>
   <div>
      <p class="myclass">This is a paragraph.</p>
      <p id="myid">This is second paragraph.</p>
      <p>This is third paragraph.</p>
   </div>
</body>
</html>

 

 

Selectors 사용법

기본적으로 셀렉터는 이름, 아이디, 클래스명으로 요소를 구분을 지어서 하나 또는 여러개를 얻어올 수 있습니다. 

SelectorDescription
NameSelects all elements which match with the given element Name.
#IDSelects a single element which matches with the given ID
.ClassSelects all elements which match with the given Class.
Universal (*)Selects all elements available in a DOM.
Multiple Elements E, F, GSelects the combined results of all the specified selectors E, F or G.

실제로 위 셀렉터들을 사용하는 방법은 아래에 많이 나와있습니다.

  • $('*'): This selector selects all elements in the document.

  • $("p > *"): This selector selects all elements that are children of a paragraph element.

  • $("#specialID"): This selector function gets the element with id="specialID".

  • $(".specialClass"): This selector gets all the elements that have the class of specialClass.

  • $("li:not(.myclass)"): Selects all elements matched by <li> that do not have class="myclass".

  • $("a#specialID.specialClass"): This selector matches links with an id of specialID and a class of specialClass.

  • $("p a.specialClass"): This selector matches links with a class of specialClass declared within <p> elements.

  • $("ul li:first"): This selector gets only the first <li> element of the <ul>.

  • $("#container p"): Selects all elements matched by <p> that are descendants of an element that has an id of container.

  • $("li > ul"): Selects all elements matched by <ul> that are children of an element matched by <li>

  • $("strong + em"): Selects all elements matched by <em> that immediately follow a sibling element matched by <strong>.

  • $("p ~ ul"): Selects all elements matched by <ul> that follow a sibling element matched by <p>.

  • $("code, em, strong"): Selects all elements matched by <code> or <em> or <strong>.

  • $("p strong, .myclass"): Selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class of myclass.

  • $(":empty"): Selects all elements that have no children.

  • $("p:empty"): Selects all elements matched by <p> that have no children.

  • $("div[p]"): Selects all elements matched by <div> that contain an element matched by <p>.

  • $("p[.myclass]"): Selects all elements matched by <p> that contain an element with a class of myclass.

  • $("a[@rel]"): Selects all elements matched by <a> that have a rel attribute.

  • $("input[@name=myname]"): Selects all elements matched by <input> that have a name value exactly equal to myname.

  • $("input[@name^=myname]"): Selects all elements matched by <input> that have a name value beginning with myname.

  • $("a[@rel$=self]"): Selects all elements matched by <a> that have rel attribute value ending with self

  • $("a[@href*=domain.com]"): Selects all elements matched by <a> that have an href value containing domain.com.

  • $("li:even"): Selects all elements matched by <li> that have an even index value.

  • $("tr:odd"): Selects all elements matched by <tr> that have an odd index value.

  • $("li:first"): Selects the first <li> element.

  • $("li:last"): Selects the last <li> element.

  • $("li:visible"): Selects all elements matched by <li> that are visible.

  • $("li:hidden"): Selects all elements matched by <li> that are hidden.

  • $(":radio"): Selects all radio buttons in the form.

  • $(":checked"): Selects all checked boxex in the form.

  • $(":input"): Selects only form elements (input, select, textarea, button).

  • $(":text"): Selects only text elements (input[type=text]).

  • $("li:eq(2)"): Selects the third <li> element

  • $("li:eq(4)"): Selects the fifth <li> element

  • $("li:lt(2)"): Selects all elements matched by <li> element before the third one; in other words, the first two <li> elements.

  • $("p:lt(3)"): selects all elements matched by <p> elements before the fourth one; in other words the first three <p> elements.

  • $("li:gt(1)"): Selects all elements matched by <li> after the second one.

  • $("p:gt(2)"): Selects all elements matched by <p> after the third one.

  • $("div/p"): Selects all elements matched by <p> that are children of an element matched by <div>.

  • $("div//code"): Selects all elements matched by <code>that are descendants of an element matched by <div>.

  • $("//p//a"): Selects all elements matched by <a> that are descendants of an element matched by <p>

  • $("li:first-child"): Selects all elements matched by <li> that are the first child of their parent.

  • $("li:last-child"): Selects all elements matched by <li> that are the last child of their parent.

  • $(":parent"): Selects all elements that are the parent of another element, including text.

  • $("li:contains(second)"): Selects all elements matched by <li> that contain the text second.

지금까지 본 셀렉터들은 어떠한 HTML/XML 요소에도 일반적으로 적용가능합니다. 예를들어 selector $("li:first") 가 <li> 태그에 적용이 된다면 $("p:first") 역시 <p> 태그에 적용이 된다는 말이죠.

 

 

 

 

 

Reference : http://www.tutorialspoint.com/jquery/jquery-selectors.htm

 

 

 

 

💻 Programming/웹프로그래밍

AJAX란? - 데이터베이스

AJAX 데이터베이스 예제

아래 예제는 AJAX를 이용해서 데이터베이스에서 읽어온 자료를 처리하는 것을 보여줍니다.

예제

form 태그가 먹히지 않는 관계로 예제는 실습하기 버튼을 눌러서 W3Schools로 가셔서 해보시기 바랍니다.

실습하기 »

예제 설명 - showCustomer() 함수

사용자가 드랍다운 리스트에서 고객을 선택하면, "showCustomer()" 함수가 호출되어 실행됩니다. 이 함수는 "onchange" 이벤트가 발생하면 호출되도록 되어있습니다.

showCustomer 함수 소스 코드

function showCustomer(str) {
  var xhttp; 
  if (str == "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
  }
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
    document.getElementById("txtHint").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET""getcustomer.asp?q="+str, true);
  xhttp.send();
}

showCustomer() 함수는 아래와 같은 작업을 합니다.

  • customer가 선택이 되었는지 검사합니다.
  • XMLHttpRequest 객체를 생성합니다.
  • 서버로부터 응답을 받고나서 실행될 함수를 정의합니다.
  • 서버에 있는 파일로 요청을 보냅니다.
  • 요청을 보낼 때 파라미터 "q" 와 드랍다운 리스트에서 읽어온 str을 URL에 추가했습니다.

 AJAX Server Page

위 예제에서 사용된 서버페이지는 "getcustomer.asp"입니다.


서버 페이지 파일은 PHP, JSP와 같은 다른 서버 언어로도 구현할 수 있습니다.


PHP로 구현한 동일한 기능의 소스 보기


 "getcustomer.asp" 는 데이터베이스의 정보를 조회하고 읽어온 정보를 HTML 테이블에 넣는 기능을 합니다.

<%
response.expires=-1
sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID="
sql=sql & "'" & request.querystring("q") & "'"

set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/datafolder/northwind.mdb"))
set rs=Server.CreateObject("ADODB.recordset")
rs.Open sql,conn

response.write("<table>")
do until rs.EOF
  for each x in rs.Fields
    response.write("<tr><td><b>" & x.name & "</b></td>")
    response.write("<td>" & x.value & "</td></tr>")
  next
  rs.MoveNext
loop
response.write("</table>")
%>


자, 큰 그림이 그려지나요?

정리를 한번 해드리자면,

1. 드랍다운 리스트에서 항목을 선택한다.
2. 항목이 선택되면 onchange 이벤트에의해 showCustomer() 함수를 호출하여 ajax 요청이 서버로 전송되고
3. 서버에서 getcustomer.asp파일이 실행이 되는데 이 파일은 DB를 조회해서 읽어온 정보를 html형태의 테이블을 만들어서 응답으로 보냅니다.
4. 그러면 이 응답으로 받은 html형식의 정보를 드랍다운 리스트 아래쪽에 뿌려줍니다.

이런식으로 ajax를 이용한 요청이 처리가 되는 겁니다.

별로 어렵지 않죠? ^-^ 

여기서 AJAX 포스팅은 마치도록 하겠습니다.

참고로 AJAX포스팅에 사용된 자료는 W3Schools에 있는 자료를 번역해놓은 수준입니다.

궁금한게 있으시면 댓글 달아주시면 답글 달아드리도록 하겠습니다.





💻 Programming/웹프로그래밍

AJAX란? - 이벤트 종류

onreadystatechange 이벤트

XMLHttpRequest객체는 상태정보를 가지고 있는데 readyState 속성이 그 값을 가지고 있습니다.


그리고 우리는 이 상태 정보를 보고 응답이 왔는지, 그 응답이 정상적으로 왔는지 확인할 수가 있습니다.


이 readyState 가 변할 때마다 항상 발생하는 이벤트가 있는데 그것이 바로  onreadystatechange 이벤트입니다.


XMLHttpRequest 객체의 중요한 세 가지 속성은 아래와 같습니다.

속성설명
onreadystatechange readyState 속성값이 변할 때마다 자동으로 호출될 함수 또는 함수명을 저장합니다.
readyStateXMLHttpRequest 객체의 상태를 가지고 있고, 0 에서 4 의 값을 가집니다. 
0: 요청이 초기화되지 않았습니다. 
1: 서버와 연결되었습니다.
2: 요청이 받아들여졌습니다.
3: 요청이 진행중입니다.
4: 요청이 완료되고 응답을 받았습니다.
status200: 정상
404: 페이지를 찾을 수 없습니다.


 onreadystatechange 이벤트가 발생하고 readyState가 4이며 status가 200이면 정상적으로 요청이 처리되어 응답이 온 경우이므로 이때 원하는 작업을 하시면 됩니다.

예제

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    document.getElementById("demo").innerHTML = xhttp.responseText;
  }
};
실습하기 »

Note: onreadystatechange 이벤트는 한번의 요청을 할 때 총 5번 발생합니다 (readyState가 0에서 4까지 바뀌므로).


Callback 함수 사용하기

callback 함수는 다른 함수의 파라미터로 넘겨지는 함수를 말합니다.

만약 웹사이트에 하나 이상의 AJAX 작업이 있다면, 단 하나의 표준 함수를 만들어서 XMLHttpRequest 객체를 생성하고 각각의 AJAX 작업이 있을 때마다 이 표준함수에서 호출함으로써 코드를 단순화 할 수 있습니다.

표준함수는 각각의 AJAX작업을 하는 함수를 파라미터로 넘겨받아서 이를 처리하게 됩니다.

예제

function loadDoc(cFunc) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    cFunc(xhttp);
  }
실습하기 »

 

💻 Programming/웹프로그래밍

AJAX란? - 서버로부터 응답받기

 

서버 응답

서버로부터 응답을 받기 위해서는 XMLHttpRequest객체의 responseText 또는 responseXML 속성을 사용합니다.

속성설명
responseText응답 데이터를 string으로 받습니다.
responseXML응답 데이터를 XML 로 받습니다.


responseText 속성

예제

document.getElementById("demo").innerHTML = xhttp.responseText;
실습하기 »

responseXML 속성

예제

 cd_catalog.xml 파일을 요청하고 응답으로 온 데이터 파싱하기

xmlDoc = xhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
  txt += x[i].childNodes[0].nodeValue + "<br>";
  }
document.getElementById("demo").innerHTML = txt;
실습하기 »


응답을 받는거는 했는데 그렇다면 응답이 왔는지는 어떻게 알 수 있나요? 

자, 그 부분에 대해서는 다음 포스팅에 있을 이벤트에 대해서 공부를 하고나면 아실 수 있습니다.

자, 다음 시간에는 AJAX에서 사용되는 이벤트에 대해서 알아보도록 하겠습니다.





'💻 Programming > 웹프로그래밍' 카테고리의 다른 글

AJAX란? - 데이터베이스  (0) 2016.06.12
AJAX란? - 이벤트 종류  (0) 2016.06.12
AJAX란? - 서버로 요청하기  (1) 2016.06.12
Ajax 란? - Ajax 시작하기  (1) 2016.06.12
[jQuery] 2. jQuery Basics ( 기본 )  (0) 2015.08.06

💻 Programming/웹프로그래밍

AJAX란? - 서버로 요청하기

서버로 요청하기


- 서버로 요청을 할 때에는 XMLHttpRequest객체에서 제공하는 open(), send() 메소드를 사용합니다.


예를들어, 아래처럼 사용합니다.


var xhttp = new XMLHttpRequest();

xhttp.open("GET", "URL", true);

xhttp.send();


이런 식으로 말이죠.


이때 open()과 send()의 메소드 설명은 아래와 같습니다.

메소드설명
open(method, url, async)요청 타입을 정합니다.

method: 요청 타입: GET 또는 POST
url: 서버 (파일) 위치
async: true (비동기식) 또는 false (동기식)
send()서버로 요청을 보낸다 (GET방식에서 사용)
send(string)서버로 요청을 보낸다 (POST방식에서 사용)


GET 방식과 POST방식


GET 은 POST보다 단순하고 빠르며 대부분의 경우에 사용할 수 있습니다.

하지만 아래 경우에는 꼭 POST방식으로 써야합니다:

  • A cached file is not an option (서버에 있는 파일이나 데이터베이스를 업데이트하는 경우).
  • 서버로 많은 양의 데이터 전송이 필요한 경우 (GET방식은 전송할 데이터 사이즈 제한이 있으나 POST 방식은 사이즈 제한이 없습니다).
  • (unknown characters를 포함할 수 있는) 사용자 input을 서버로 전송할 때 , POST 방식이 보안상 GET방식보다 좋습니다.

GET Requests

간단한 GET 요청:

예제1

xhttp.open("GET""demo_get.asp"true);
xhttp.send();
실습하기 »

위 예제에서는 이미 캐쉬된 결과를 볼 수도 있습니다. 그런 경우를 피하려면, 유니크 ID를 URL에 넣어주셔야 합니다.

예제2

xhttp.open("GET""demo_get.asp?t=" + Math.random(), true);
xhttp.send();
실습하기 »

GET 방식으로 요청을 보내고 싶으시면, 정보를 URL에 입력해주시면 됩니다.

예제3

xhttp.open("GET""demo_get2.asp?fname=Henry&lname=Ford"true);
xhttp.send();
실습하기 »

POST Requests

간단한 POST 요청:

예제1

xhttp.open("POST""demo_post.asp"true);
xhttp.send();
실습하기 »

HTML 형식으로 POST 요청을 하려면, setRequestHeader()를 이용하여 HTTP 헤더 정보를 넣어주시면 됩니다. 그리고 send() 메소드에 보내려는 데이터정보를 넣어주시면 됩니다.

예제2

xhttp.open("POST""ajax_test.asp"true);
xhttp.setRequestHeader("Content-type""application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
실습하기 »

The url - 서버 상의 파일 주소

open() 메소드의 url 파라미터는 서버에 위치한 파일의 주소입니다.

xhttp.open("GET""ajax_test.asp"true);

여기서 말하는 파일은 .txt, .xml 파일처럼 평범한 파일들, 또는 .asp, .php 와 같은 서버스크립팅 파일입니다.  (서버스크립팅 파일들은 서버에서 응답을 보내기 전에 특정 일을 수행할 수 있습니다.).


비동기식 - True or False?

ajax를 사용하려면 3번째 파라미터는 무조건 true여야 합니다.

xhttp.open("GET""ajax_test.asp"true);

Async=true

예제

xhttp.onreadystatechange = function() {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    document.getElementById("demo").innerHTML = xhttp.responseText;
  }
};
xhttp.open("GET""ajax_info.txt"true);
xhttp.send();
실습하기 »



Async=false

xhttp.open("GET""ajax_info.txt"false);

async=false 로 사용하게되면 더이상 AJAX를 사용하는게 아닌게 되어버립니다. 이렇게 서버로 요청을 하게되면 서버에서 응답이 오기 전까지 화면에서 아무것도 할 수 없는 상황이 발생합니다.

예제

xhttp.open("GET""ajax_info.txt"false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
실습하기 »



자, 지금까지 AJAX를 이용한 서버로 요청 보내기에 대해서 알아보았습니다.

다음 포스팅에서는 응답을 받는 것에 대해서 알아보도록 하겠습니다.