○ css()
- css() : jQuery에서 스타일 접근 함수
<div id="mydiv" style="position: relative;
background: darksalmon;">대한민국</div>
<script>
//JavaScript에서 스타일 접근
document.getElementById("mydiv").style;
document.getElementById("mydiv").style.position;
document.getElementById("mydiv").style.background;
//jQuery에서 스타일 접근
$("#mydiv").css("position");
$("#box").css("background");
</script>
- 형식 (jQuery에서는 대부분 getter와 setter함수 개념을 같이 사용)
① $(선택자).css(속성명); : getter 개념
② $(선택자).css(속성명, 속성값); : setter 개념
③ $(선택자).css({속성명:속성값, 속성명:속성값, 속성명:속성값, ... }); : 여러 개의 속성을 한꺼번에 세팅(JSON)
<head>
<meta charset="UTF-8">
<title>css메소드</title>
<script src="jquery-3.6.0.min.js"></script>
<style>
#box{
width: 400px;
height: 300px;
border: 1px solid #000;
}
</style>
</head>
<body>
<p>
<button>색상입력</button>
<button>크기얻기</button>
<button>여러개의 속성을 한번에 변경</button>
</p>
<div id="box"></div>
<script>
//<body>에 있는 <button>요소들 중에서 0번째 접근
$("button:eq(0)").click(function(){
$("#box").css("background", "yellow"); //배경색 노랑으로 설정
});
$("button:eq(1)").click(function(){
var width = $("#box").css("width"); //400px
var height = $("#box").css("height"); //300px
});
$("button:eq(2)").click(function(){ //여러 속성 한번에 변경
var width=800;
$("#box").css({ "width":width
,height:600
,"background":"url(../images/k7.png)"
,"border":"50px dotted blue"
});
});
</script>
<body>
○ prop()와 attr()
- 요소의 속성에 접근하는 함수 ( property → prop() / attribute → attr() )
<img src="../image/k7.png" alt="라이언" title="ryan"/>
- <img> → 요소(element)
- src, alt, title → 속성(attribute)
<body>
<p>
<button>title얻기</button>
<button>src변경</button>
<button>여러개의 속성을 변경</button>
</p>
<img src="../image/k7.png" alt="라이언" title="ryan"/>
<script>
$("button:eq(0)").click(function(){//<img>요소의 title속성값 얻기
var title=$("img").attr("title");
alert(title);
});
$("button:eq(1)").click(function(){//<img>요소의 src변경
$("img").attr("src", "../image/k6.png");
});
$("button:eq(2)").click(function(){//<img>요소의 여러 속성 동시 변경
var obj={ "width":400
,"height":400
,"src":"../image/k2.png"
,"alt":"어피치"
,"title":"apeach"
};
$("img").attr(obj);
});
</script>
</body>
○ property와 attribute의 차이
- attribute : html 문서 안에서의 정적인(바뀌지 않는) 속성
- property : html DOM 안에서 동적인(바뀌는) 속성(또는 그 값)
'Frontend > jQuery' 카테고리의 다른 글
06. jQuery, this & index (0) | 2022.06.07 |
---|---|
05. jQuery, each반복문 (0) | 2022.06.07 |
03. jQuery, text()와 html() 함수 / jQuery Method Chaining (0) | 2022.06.03 |
02. jQuery, Event (이벤트 처리, 이벤트 종류) (0) | 2022.06.03 |
01. jQuery 시작 (오픈소스 사용방법, 기본 문법) (0) | 2022.06.03 |
댓글