jQuery

[HTML_CSS] JQ - width() 메서드 ★★★ - 요소 너비 설정/반환. (= width메서드 = 위드스메서드)

목차

  1. width() 예제 - 너비 반환
  2. width() 정의
  3. width() 구문
  4. width() 예제 - 너비 설정
  5. width() 예제 - 함수 사용해 너비 줄이기
  6. width() 예제 - window 및 document 요소 너비 반환
  7. width() 예제 - 관련 메서드와 비교
  8. width() 예제 - 반응형 배경색
  9. width() 예제 - 해상도 768px 이하 시 파일명에 _m 붙이기

 

width() 예제 - 너비 반환

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

  $("button").click(function(){

    alert("div 너비: " + $("div").width());

  });

});

</script>


<style>

div {

    height:100px;

    width:200px;

    padding:10px;

    margin:20px;

    border:1px solid blue;

    background-color:yellow;

}

</style>


<div style=""></div>

<button>클릭</button>

 

결과보기

결과값: div 너비: 200

 

width() 정의

 

선택 요소의 너비를 설정/반환.

 



1. 

반환 경우 : 선택자와 첫 번째로 일치하는 요소의 너비를 반환.

설정 경우 : 선택자와 일치하는 모든 요소의 너비를 설정.


2.

주의: (padding, border, margin) 값은 포함 X

 

3. 

width() - 선택요소의 너비 반환/설정.

innerWidth() - (width + padding) 반환.

outerWidth() - (width + padding + border) 반환.

outerWidth(true) - (width + padding + border + margin) 반환.

 

height() - 선택요소의 높이 반환/설정.

innerHeight() - (height + padding) 반환.

outerHeight() - (height + padding + border) 반환.

outerHeight(true) - (height + padding + border + margin) 반환.

 

 

width() 구문


너비 반환

$(selector).width()

 

너비 설정

$(selector).width(value)

$(selector).width(function(index,currentwidth))

 


[매개변수]

 

value

필수. 설정할 너비값.

※ 너비를 px, em, pt 등으로 지정. (기본 단위: px)

※ px가 아닌 em, pt 등 단위 붙일 땐, 큰따옴표(" ")로 감쌈.

※ px는 기본 단위라서, 따로 단위 붙일 필요없이 숫자만 입력.


function (index, currentwidth)

선택. 선택 요소의 새 너비를 반환하는 함수.


index

집합에서 요소의 인덱스 (= 색인 번호) 위치를 반환.


currentwidth

선택 요소의 현재 너비를 반환.

 

 

width() 예제 - 너비 설정

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

  $("#btn1").click(function(){

    $("div").width(400);

  });

  $("#btn2").click(function(){

    $("div").width("30em");

  });

  $("#btn3").click(function(){

    $("div").width("200pt");

  });

});

</script>


<style>

div {

    height:100px;

    width:200px;

    padding:10px;

    margin:20px;

    border:1px solid blue;

    background-color:yellow;

}

</style>


<button id="btn1">400px 설정</button>

<button id="btn2">30em 설정</button>

<button id="btn3">200pt 설정</button>


<div></div>

 

결과보기

 

width() 예제 - 함수 사용해 너비 줄이기

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

  $("button").click(function(){

    $("div").width(function(n, c){

      return c - 200;

    });

  });

});

</script>


<style>

div {

    height:100px;

    border:4px solid;

    margin:10px;

}

</style>


<button>너비를 200px 줄이기.</button><br><br>


<div></div>

<div></div>

 

결과보기

PS. 첫 번째 요소만 너비 줄이기: if(n ==0) return c - 200;

 

width() 예제 - window 및 document 요소 너비 반환

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

  $("button").click(function(){

    $("#span1").text($(window).width());

    $("#span2").text($(document).width());

  });

});

</script>


<p>window 너비: <span id="span1">?</span> px.</p>

<p>document 너비:  <span id="span2">?</span> px.</p>


<button>window 및 document 요소의 너비 반환</button>

 

결과보기

 

width() 예제 - 관련 메서드와 비교

 

<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: " + $("#hz").width() + "</br>";

    txt += "innerWidth: " + $("#hz").innerWidth() + "</br>";

    txt += "outerWidth: " + $("#hz").outerWidth() + "</br>";

    txt += "outerWidth (margin 포함O): " + $("#hz").outerWidth(true) + "</br>" + "</br>";

  

    txt += "height: " + $("#hz").height() + "</br>";   

    txt += "innerHeight: " + $("#hz").innerHeight() + "</br>";

    txt += "outerHeight: " + $("#hz").outerHeight() + "</br>";

    txt += "outerHeight(margin 포함): " + $("#hz").outerHeight(true) + "</br>";

    $("#hz").html(txt);

  });

});

</script>


<style>

#hz {

    height:300px;

    width:300px;

    padding:10px;

    margin:4px;

    border:2px solid blue;

    background-color:lightblue;

}

</style>


<div id="hz"></div>

<button>클릭</button>

 

결과보기

 

width() 예제 - 반응형 배경색

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function() {

  $(window).resize(function() {

    if ($(this).width() < 769) {

      $("body").css("background-color", "yellow");

    } else {

      $("body").css("background-color", "pink");

    }

  });

});

</script>

 

<p>창 너비 조절해 배경색 변동 확인</p>

 

결과보기

 

width() 예제 - 해상도 768px 이하 시 파일명에 _m 붙이기

※ 엄밀히 따지면, 이미지 크기가 768px 이하 시 _m 붙임.

 

<script src="https://code.jquery.com/jquery-latest.js"></script>


<img id="a" class="hz" src="./img/a.jpg">

<img id="b" class="hz" src="./img/b.jpg">


<script>

$(function() {

    $("img.hz").each(function() {

        if ($(this).width() < 768) {

            const id = $(this).attr('id');

            $(this).attr('src', './img/'+id+'_m.jpg');

        }

    });

});

</script>

 

평정심 님 (210822) https://sir.kr/qa/427359



분류 제목
Event JQ - one() 메서드 - 요소마다 오직 한번만 이벤트 실행. (= one메서드 = 원메서드) ※ 현재값…
Event JQ - $.proxy() 메서드 - 기존 함수를 가져와 특정 구문을 가진 새 함수로 반환. (= proxy…
Event JQ - ready() 메서드 - DOM이 완전 로드 시 실행할 함수 지정. (= ready메서드 = 레디 …
Event JQ - resize() 메서드 - 창크기변경이벤트 (= 윈도우창 리사이즈이벤트 = resize메서드 = 리…
Event JQ - scroll() 메서드 ★★★ - 스크롤 이벤트를 부착/촉발 (jquery, scroll, even…
Event JQ - select() 메서드 - 입력창의 문자열 드래그 선택. (= select이벤트 = 실렉트/셀렉트 …
Event JQ - submit() 메서드 ★ - 폼 입력값 전송 이벤트 촉발/실행함수 지정. (= submit메서드 …
Event JQ - toggle() 메서드 - JQ 1.9 폐기완료. / 여러 클릭 이벤트간 상호전환. (= togg…
Event JQ - trigger() 메서드 ★ - 지정 이벤트 수동 촉발과 이벤트 기본동작 수행. (= trigger…
Event JQ - triggerHandler() 메서드 - 지정 이벤트 수동 촉발만 함. (= 트리거핸들러 메서드)
Event JQ - unbind() 메서드 - JQ 3.0 폐기예고, off() 메서드로 대체. 추가된 이벤트핸들러 제…
Event JQ - undelegate() 메서드 - JQ 3.0 폐기예고. off() 메서드로 대체. / 이벤트핸들러…
Event JQ - unload() 메서드 - JQ 3.0 폐기완료. / 페이지 떠날 때 실행. (= 언로드 메서드)
Effect JQ - clearQueue() 메서드 - 선택요소에서 실행 대기 함수 모두 제거/삭제. (= clearQu…
Effect JQ - delay() 메서드 - 실행 대기 함수의 실행을 지연. (= delay메서드 = 딜레이메서드)
10/20
목록
 홈  PC버전 로그인 일본어
그누앞단언어
그누뒷단언어
그외코딩언어
그누보드
제작의뢰
Q&A
커뮤니티 2
웹유틸
회원센터
홈짱닷컴 PC버전 로그인