developer tip

jQuery를 사용하여 너비와 높이를 동적으로 설정하는 방법

copycodes 2020. 11. 14. 10:45
반응형

jQuery를 사용하여 너비와 높이를 동적으로 설정하는 방법


divjQuery를 사용하여 요소 의 너비와 높이를 동적으로 설정하고 싶습니다 .

나는 교체하려고했다

<div id="mainTable" style="width:100px; height:200px;"></div>

이것으로 :

$("#mainTable").css("width", "100");
$("#mainTable").css("height", "200");

그러나 그것은 나를 위해 작동하지 않습니다.

이유를 이해하도록 도와주세요.

다들 감사 해요 !

문제는 숫자의 인용 부호에있었습니다. 이것은 잘 작동합니다.

$("#mainTable").css("width", 100);
$("#mainTable").css("height", 200);

다음과 같이 할 수 있습니다.

$(function() {
  $("#mainTable").width(100).height(200);
});

여기에는 두 가지 변경 사항이 있으며 이제 .width()및을 사용 하고 이벤트 .height()에서 코드를 실행합니다 document.ready.

$(function() { })래퍼가 없으면 (또는 $(document).ready(function() { })원하는 경우) 요소가 아직 존재하지 않을 수 있으므로 $("#mainTable")아무것도 찾을 수 없습니다. 여기에서 작동하는 예를 볼 수 있습니다 .


@Misha Moroshko가 이미 자신을 게시 했으므로 다음과 같이 작동합니다.

$("#mainTable").css("width", 100);
$("#mainTable").css("height", 200);

@Nick Craver의 허용 된 답변보다이 기술에는 몇 가지 이점이 있습니다. 다른 단위를 지정할 수도 있습니다.

$("#mainTable").css("width", "100%");

따라서 @Nick Craver의 방법은 실제로 일부 사용자에게는 잘못된 선택 일 수 있습니다. jquery API ( http://api.jquery.com/width/ )에서 :

.css (width)와 .width ()의 차이점은 후자는 단위가없는 픽셀 값 (예 : 400)을 반환하는 반면 전자는 단위가 그대로있는 값 (예 : 400px)을 반환한다는 것입니다. .width () 메서드는 수학적 계산에 요소의 너비를 사용해야 할 때 권장됩니다.


이 시도:

<div id="mainTable" style="width:100px; height:200px;"></div> 

$(document).ready(function() {
  $("#mainTable").width(100).height(200);
}) ;

나는 코드 아래에서 잘 작동했다.

var modWidth = 250;
var modHeight = 150;

아래 예 :-

$( "#ContainerId .sDashboard li" ).width( modWidth ).height(modHeight);

또는 다음 구문을 사용하십시오.

$("#mainTable").css("width", "100px");
$("#mainTable").css("height", "200px");

위의 모든 제안을 시도했지만 그들 중 어느 것도 나를 위해 일하지 않았으며 실제 너비와 높이가 아닌 clientWidth 및 clientHeight를 변경했습니다.

The jQuery docs for $().width and height methods says: "Note that .width("value") sets the content width of the box regardless of the value of the CSS box-sizing property."

The css approach did the same thing so I had to use the $().attr() methods instead.

_canvas.attr('width', 100);
_canvas.attr('height', 200);

I don't know is this affect me because I was trying to resize a element and it is some how different or not.

참고URL : https://stackoverflow.com/questions/2722068/how-to-set-width-and-height-dynamically-using-jquery

반응형