2012-10-19

Javascript : CSS 특성 바꾸기+ [Javascript: Changing CSS attribute values]

참고 페이지 : http://lonelycat.tistory.com/312

정규 교육이라는 걸 받아본 일 없이 프로그래밍을 하다 보니 노가다는 필수다. 이번에는 HTML 상에 표현된 개체의 특성을 바꾸어 보려고 하는데, 가장 초보적인 배경색 바꾸기 문제다.

의외로 매우 간단한데, 알아야 될 것은 setAttribute 라는 것 뿐인 셈이다. id를 이용해서 해당 element를 얻은 후 setAttribute 명령어로 속성을 바꾸어준다. CSS에서 글자색, 배경색 등 속성은 <... style="background-color:blue> 등으로 표시되니, 이걸 잡아서 바꾸어주면 되겠다. 물론 다른 속성들도 바꾸기 편하고, 특히 이 부분은 javascript로 표현이 되니 mouse 이벤트와 묶을 수 있는 장점도 있다.

function showAttr(nID, content) {
document.getElementById(nID).setAttribute("style", "background-color:"+content);
}

주 : 엉뚱한 문제로 구현에 어려움을 겪었는데, 만일 함수 이름에 'Style'이라는 말이 들어가면 적절하게 작동하지 않는다. 아마도 javascript나 HTML 예약어를 다시 공부해야 할 듯.

Actually I have no experience to study any programming language in a school, so need to effort such as browsing information on the Web and meeting failure. Today want to change the attributes of a HTML object, such as changing background color.

Truly simple when you know the command 'setAttribute'. Following code shows the action of finding an object using id then changing 'style' attribute using 'setAttribute' command. CSS sets the attributes of text using <... style="background-color:blue>, so it's really simple to change those. Especially this javascript code can be useful when binding together with mouse event.

function showAttr(nID, content) {
document.getElementById(nID).setAttribute("style", "background-color:"+content);
}


Note: Takes time due to unknown errors when making this function, that you cannot use the term 'Style' in the title of this function (such as function showStyle(...)). I guess that term is one of reserved words in javascript or HTML... need more study.

2 comments:

  1. 수고많네^^(나다 지훈이)
    -보통 Style에 다른 항목도 있으니 다음과 같이 하지 않나?
    document.getElementById(nID).style.backgroundColor = content;
    - 좀더 표준화 시킨다면 CSS클래스 2개 만들고 치환하거나...
    - showStyle()이 예약어는 아닌듯 한데...다른 함수 만든거랑 충돌나는거 아닌지?

    ReplyDelete
    Replies
    1. 네 첫번째 댓글인 것 같은데? 매우 감사히 생각합니다, 팀장님.
      - style만 사용하는 게 아니라 다른 요소들도 바꿔볼까 하고 이렇게 했네 그려. 하지만 보여준 예도 유용하게 사용할 수 있겠네 그려.
      - 그거 방지하려고 .js 라이브러리를 사용하고 있는데, 충돌도 없는데 작동이 안되서 그랬음. 아직도 원인을 찾지 못했다.

      Delete