[jQuery] API Documentation : .css()

https://api.jquery.com/css/

 


Examples [1]
Get the background color of a clicked div.

(1) 각각의 div를 60px의 정사각형으로 만들어 한 줄로 5px 간격으로 좌측 정렬
(2) 각각 div를 다음과 같이 배경색 입력
    첫 번째 div는 blue, 두 번째 div는 green, 세 번째 div는 navy, 네 번째 div는 red
(3) 각각 div를 클릭하면 span 태그 영역에 해당 div의 배경색 rgb 코드를 출력

▼ 예제 상세 보기 및 답안
https://api.jquery.com/css#example-0

 

▼ 나의 풀이

- div의 크기와 색을 입력하는 것을 css대신 jQuery의 .css() 이용(키체인)

- div의 배경색을 하나하나 주지 않고 수업시간에 배운 jQuery의 메서드가 순회하는 것을 이용

- <span> 태그 문장 바꾸는 법(.html)을 몰라서 답안 참고함

<body>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <span></span>
    <script>
        $(function() {
            var colors = ["blue", "green", "navy", "red"];
            $("div")
            .css({width: "60px", height: "60px", "margin-right": "5px", float: "left"})
            .css("background-color", function(index) {
                return colors[index%colors.length];
            })
            .click(function() {
                var color = $(this).css("background-color");
                $("span").html("That div is <span style='color:" +
                    color + ";'>" + color + "</span>." );
            });
        });
    </script>
</body>

 

 

 


Examples [2]
Get the width, height, text color, and background color of a clicked div.
(1) 첫 번째 div는 가로 50px, 세로 50px, 글자색은 yellow, 배경색은 blue
(2) 두 번째 div는 가로 80px, 세로 50px, 글자색은 white, 배경색은 green
(3) 세 번째 div는 가로 40px, 세로 50px, 글자색은 pink, 배경색은 navy
(4) 네 번째 div는 가로 70px, 세로 50px, 글자색은 black, 배경색은 red
(5) 네 개의 div를 한 줄로 5px 간격으로 좌측 정렬
(6) 각각의 div를 클릭하면 p 태그 영역에 해당 div의 가로, 세로, 글자색, 배경색을 출력

▼ 예제 상세 보기 및 답안
https://api.jquery.com/css#example-1

 

▼ 나의 풀이

- 답안을 보지 않고 push만을 이용(주석 부분)해서 풀이

- 답안 참고하여 $.each로 정리했지만, $가 어떤 객체인지 콘솔 찍어봐도 모르겠음 < 선생님께 질문할 것

<body>
    <p></p>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <script>
        $(function() {
            var widths = ["50px", "80px", "40px", "70px"];
            var colors = ["yellow", "white", "pink", "black"];
            var backColors = ["blue", "green", "navy", "red"];
            $("div")
            .css("width", function(index) {
                return widths[index%widths.length];
            })
            .css("color", function(index) {
                return colors[index%colors.length];
            })
            .css("background-color", function(index) {
                return backColors[index%backColors.length];
            })
            .css({heigh: "60px", "margin-right": "5px", float: "left"})
            .click(function() {
                var str = ["The clicked div has the following styles:"];
                // str.push("<br>width: " + $(this).css("width"));
                // str.push("<br>height: " + $(this).css("height"));
                // str.push("<br>color: " + $(this).css("color"));
                // str.push("<br>background-color: " + $(this).css("background-color"));
                var str2 = $(this).css(["width", "height", "color", "background-color"]);
                $.each(str2, function(prop, value){ // ★
                    str.push("<br>" + prop + ": " + value);
                })
                $("p").html(str);
            });
        });
    </script>
</body>

 

 

 


Examples [3]
Change the color of any paragraph to red on mouseover event.
(1) p 태그의 너비는 200px, 글자색은 blue, 글자크기는 14px
(2) 마우스를 p 태그에 올리면 글자색이 red로 바뀜

▼ 예제 상세 보기 및 답안
https://api.jquery.com/css#example-1-0

 

▼ 나의 풀이

- .on("mouseover", function(){}); 답안 보고함

<body>
    <p>Just roll the mouse over me.</p>
    <p>Or me to see a color change.</p>
    <script>
        $(function() {
            $("p")
            .css({width: "200px", color: "blue", fontSize: "14px"})
            .on("mouseover", function() {
                $(this).css("color", "red");
            });
        });
    </script>
</body>

 

 

 


Examples [4]
Increase the width of #box by 200 pixels the first time it is clicked.
(1) div의 배경색 black, 글자색 white, 너비 200px, 패딩 10px
(2) 처음 클릭할 때 p 태그의 너비를 200px 증가

▼ 예제 상세 보기 및 답안
https://api.jquery.com/css#example-1-1

 

▼ 나의 풀이

- .one("click", function() {}); 답안 보고함

- 어째서 200이 아닌 200px 문자열과 +=200 문자열의 결합이 400px이 되는 걸까.

 (선생님 : jQuery의 css()메서드는 값을 조회할때 px을 제외하고 숫자 200을 반환하고, 

     +=200 을 계산 한 뒤, 다시 값을 지정할 때 숫자를 문자열로 바꾸고 뒤에 붙인다. 

     교재 <자바스크립트 완벽가이드 644p> 참고.)

<body>
    <p>Click me to grow.</p>
    <script>
        $(function() {
            $("p")
            .css({backgroundColor: "black", color: "white", width: "200px"
            				, padding: "10px", fontSize: "14px"})
            .one("click", function() {
                $(this).css("width", "+=200") // ★
            });
        });
    </script>
</body>

 

 

 


Examples [5]
Highlight a clicked word in the paragraph.
(1) P 태그의 글자색을 blue, font-weight를 진하게, 커서를 pointer로
(2) p태그의 단어를 클릭하면 노란색 배경으로 강조 표시

    p태그의 문장을 단어별로(띄어쓰기 단위로) <span> 태그로 분리하여

   각 <span> 태그가 클릭될 때 노란색 배경으로 바뀌게 됨

▼ 예제 상세 보기 및 답안
https://api.jquery.com/css#example-1-2

 

▼ 나의 풀이

- 문장을 단어 단위로 분리하여 배열화 하는 부분 답안 보고함

<body>
    <p>
        Once upon a time there was a man
        who lived in a pizza parlor. This
        man just loved pizza and ate it all
        the time. He went on to be the
        happiest man in the world. The end.
    </p>
    <script>
        $(function() {
            $("p")
            .css({color: "blue", fontWeight: "bold", cursor: "pointer"});
            var words = $("p").text().split(/\s+/); // ★
            var text = words.join("</span> <span>"); // ★
            $("p").html("<span>" + text + "</span>");
            $("span").click(function() {
                $(this).css("background-color", "yellow");
            });
        });
    </script>
</body>

 

 

 


Examples [6]
Change the font weight and background color on mouseenter and mouseleave.
(1) p 태그 글자색 green
(2) p 태그에 마우스 포인터를 올리면 글자가 진해지고 배경색이 노란색으로 바뀜
  .on("mouseenter", function() {}); 이용
(2) p 태그에서 마우스 포인터가 떠나면 배경이 회색으로 바뀜 
  .on("mouseleave", function() {}); 이용

▼ 예제 상세 보기 및 답안
https://api.jquery.com/css#example-1-3

 

▼ 나의 풀이

<body>
    <p>Move the mouse over a paragraph.</p>
    <p>Like this one or the one above.</p>
    <script>
        $(function() {
            $("p")
            .css("color", "green")
            .on("mouseenter", function() {
                $(this)
                .css("font-weight", "bold")
                .css("background-color", "yellow");
            })
            .on("mouseleave", function() 
                $(this)
                .css("font-weight", "normal")
                .css("background-color", "lightgray");
            });
        });
    </script>
</body>

 

 

 


Examples [6]
Increase the size of a div when you click it.
(1) 두 개의 div의 너비를 20px, 높이를 15px, 배경색을 red
(2) div를 클릭할 때마다 너비와 높이가 각각 1.2배씩 증가 

▼ 예제 상세 보기 및 답안
https://api.jquery.com/css#example-1-4

 

▼ 나의 풀이

- 4번 예제에서 += 200은 되고 *=1.2는 안되는 걸까? 속성선택자 때문?

 (선생님: 속성선택자 때문이라기 보다는 많이 사용하지 않는 것이라 Parsing되지 않은 것)

<body>
    <div>click</div>
    <div>click</div>
    <script>
        $(function() {
            $("div")
            .css("width", "20px")
            .css("height", "15px")
            .css("background-color", "red")
            .on("click", function() {
                $(this).css({
                    width: function(index, value) {
                        return parseFloat(value) * 1.2;
                    },
                    height: function(index, value) {
                        return parseFloat(value) * 1.2;
                    }
                })
            })
        });
    </script>
</body>