jQuery/html

jQuery: CSS classes, dimensions

carrot62 2020. 7. 31. 01:51
  • addClass()
    • 여러 class 한번에 적용 가능하다 
          예) $("div").addClass("class1 class2 class3")
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("h1, h2, p").addClass("blue");
    $("div").addClass("important");
  });
});
</script>
<style>
.important {
  font-weight: bold;
  font-size: xx-large;
}

.blue {
  color: blue;
}
</style>
</head>
<body>

<h1>Heading 1</h1>
<h2>Heading 2</h2>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<div>This is some important text!</div><br>

<button>Add classes to elements</button>

</body>
</html>
  • removeClass()
  • toggleClass()

 

  • css(): element의 css 속성을 받아온다 (여러 element일 경우에는 첫번째 element의 속성을 받아온다)
css("propertyname");

css 속성을 지정해줄 때 문법:

css("propertyname","value");
//여러 속성을 지정하고 싶다면
css({"propertyname":"value","propertyname":"value",...});

jQuery Dimensions

  • width()
  • height()
  • innerWidth()
  • indderHeight()
  • outerWidth()
  • outerHeight()

width와 height 값을 리턴해주는 예제:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    var txt = "";
    txt += "Width of div: " + $("#div1").width() + "</br>";
    txt += "Height of div: " + $("#div1").height();
    $("#div1").html(txt);
  });
});
</script>
<style>
#div1 {
  height: 100px;
  width: 300px;
  padding: 10px;
  margin: 3px;
  border: 1px solid blue;
  background-color: lightblue;
}
</style>
</head>
<body>

<div id="div1"></div>
<br>

<button>Display dimensions of div</button>

<p>width() - returns the width of an element.</p>
<p>height() - returns the height of an element.</p>

</body>
</html>