HTML 요소의 실제 너비와 높이를 검색하려면 어떻게 해야 합니까?
, 내가 ★★★★★★★★★★★★★★★★★★★★★★.<div>
브라우저의 디스플레이(뷰포트) 가운데에 두고 싶다.위해서는 가로, 세로, 세로, 가로, , , 세로, 가로, 세로, 가로, 세로, 가로, 세로, .<div>
★★★★★★ 。
뭘로 할까요?브라우저 호환성에 대한 정보를 포함하십시오.
및 속성을 사용해야 합니다.주의: 이들은 엘리먼트에 속하지 않습니다..style
.
var width = document.getElementById('foo').offsetWidth;
함수는 CSS 변환을 수행한 후 요소의 치수와 위치를 부동소수점 숫자로 반환합니다.
> console.log(document.getElementById('foo').getBoundingClientRect())
DOMRect {
bottom: 177,
height: 54.7,
left: 278.5,
right: 909.5,
top: 122.3,
width: 631,
x: 278.5,
y: 122.3,
}
를 참조해 주세요.
this this 、 음음 。width
,height
「 」 「 」 :
{
width: 960,
height: 71,
top: 603,
bottom: 674,
left: 360,
right: 1320
}
예:
var element = document.getElementById('foo');
var positionInfo = element.getBoundingClientRect();
var height = positionInfo.height;
var width = positionInfo.width;
것 요..offsetWidth
★★★★★★★★★★★★★★★★★」.offsetHeight
0
(여기 코멘트 참조)
다른 은 '하다'입니다.getBoundingClientRect()
는 소수 픽셀을 할 수 서 부픽 、 분픽 、 ,,,,,,픽셀을 반환할 수 있습니다..offsetWidth
★★★★★★★★★★★★★★★★★」.offsetHeight
가장 가까운 정수로 반올림합니다.
IE8 주의:getBoundingClientRect
IE8 이하에서는 높이와 폭이 반환되지 않습니다.*
IE8을 지원해야 하는 경우.offsetWidth
★★★★★★★★★★★★★★★★★」.offsetHeight
:
var height = element.offsetHeight;
var width = element.offsetWidth;
이 메서드에 의해 반환된 객체는 실제로는 일반 객체가 아닙니다.속성은 열거할 수 없습니다(예:Object.keys
즉시 사용할 수 없습니다.)
자세한 내용은 이쪽:ClientRect/DomRect를 플레인 객체로 변환하는 최선의 방법
레퍼런스:
.offsetHeight
: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight.offsetWidth
: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth.getBoundingClientRect()
: https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
메모: 이 답변은 2008년에 작성되었습니다. 당시 대부분의 사람들에게 최고의 크로스 브라우저 솔루션은 jQuery를 사용하는 것이었습니다. 후세를 위해 여기에 답을 남깁니다. 만약 jQuery를 사용한다면, 이것은 좋은 방법입니다. 다른 프레임워크나 순수 JavaScript를 사용하고 있다면 아마도 받아들여진 답변이 최선의 선택일 것입니다.
jQuery 1.2.6에서는 핵심 CSS 기능 중 하나를 사용할 수 있습니다.height
★★★★★★★★★★★★★★★★★」width
(오류)outerHeight
★★★★★★★★★★★★★★★★★」outerWidth
(일부러)
var height = $("#myDiv").height();
var width = $("#myDiv").width();
var docHeight = $(document).height();
var docWidth = $(document).width();
누구에게나 도움이 될까봐 텍스트 박스, 버튼, div를 모두 같은 css로 넣었습니다.
width:200px;
height:20px;
border:solid 1px #000;
padding:2px;
<input id="t" type="text" />
<input id="b" type="button" />
<div id="d"></div>
하거나 사용하지 않고 또, jquery, jquery, jquery를 하지 않고 했습니다.box-sizing:border-box
함께.<!DOCTYPE html>
결과:
Firefox Chrome IE-Edge
with w/o with w/o with w/o box-sizing
$("#t").width() 194 200 194 200 194 200
$("#b").width() 194 194 194 194 194 194
$("#d").width() 194 200 194 200 194 200
$("#t").outerWidth() 200 206 200 206 200 206
$("#b").outerWidth() 200 200 200 200 200 200
$("#d").outerWidth() 200 206 200 206 200 206
$("#t").innerWidth() 198 204 198 204 198 204
$("#b").innerWidth() 198 198 198 198 198 198
$("#d").innerWidth() 198 204 198 204 198 204
$("#t").css('width') 200px 200px 200px 200px 200px 200px
$("#b").css('width') 200px 200px 200px 200px 200px 200px
$("#d").css('width') 200px 200px 200px 200px 200px 200px
$("#t").css('border-left-width') 1px 1px 1px 1px 1px 1px
$("#b").css('border-left-width') 1px 1px 1px 1px 1px 1px
$("#d").css('border-left-width') 1px 1px 1px 1px 1px 1px
$("#t").css('padding-left') 2px 2px 2px 2px 2px 2px
$("#b").css('padding-left') 2px 2px 2px 2px 2px 2px
$("#d").css('padding-left') 2px 2px 2px 2px 2px 2px
document.getElementById("t").getBoundingClientRect().width 200 206 200 206 200 206
document.getElementById("b").getBoundingClientRect().width 200 200 200 200 200 200
document.getElementById("d").getBoundingClientRect().width 200 206 200 206 200 206
document.getElementById("t").offsetWidth 200 206 200 206 200 206
document.getElementById("b").offsetWidth 200 200 200 200 200 200
document.getElementById("d").offsetWidth 200 206 200 206 200 206
offsetWidth
★★★★★★★★★★★★★★★★★」offsetHeight
', 경우패딩 및를 포함한 가 차지하는 공간의합니다.
clientWidth
★★★★★★★★★★★★★★★★★」clientHeight
return 테두리여백 하지 않음)'은 '사용하지 않음', '사용하지 않음', '사용하지 않음', '사용하지 않음'입니다.
scrollWidth
★★★★★★★★★★★★★★★★★」scrollHeight
' '내용물의 한다.
따라서 측정된 내용이 현재 표시 가능 영역을 벗어날 것으로 예상되는지 여부에 따라 달라집니다.
IE7 이상에 대해서만 계산하면 됩니다(콘텐츠의 크기가 고정되어 있지 않은 경우에만).CSS2를 지원하지 않는 오래된 IE에 대한 해킹을 제한하기 위해 HTML 조건부 코멘트를 사용하는 것이 좋습니다.다른 모든 브라우저의 경우 다음을 사용합니다.
<style type="text/css">
html,body {display:table; height:100%;width:100%;margin:0;padding:0;}
body {display:table-cell; vertical-align:middle;}
div {display:table; margin:0 auto; background:red;}
</style>
<body><div>test<br>test</div></body>
이치노★★를 으로 하고 .<div>
을 사용하다
요소 스타일을 수정하는 것은 쉽지만 값을 읽기에는 다소 까다롭습니다.
JavaScript에서 getComputedStyle을 호출하는 임베디드 메서드를 사용하지 않는 한 JavaScript는 css(internal/external)에서 나오는 요소 스타일 속성(elem.style)을 읽을 수 없습니다.
getComputedStyle(element[, 의사])
요소:값을 읽을 요소.
pseudo: 필요한 경우 유사 요소(예:: before).빈 문자열 또는 no 인수는 요소 자체를 의미합니다.
그 결과 elem.style과 같은 스타일 속성을 가진 객체가 생성되지만, 모든 css 클래스에 대해 적용됩니다.
예를 들어, 다음 스타일은 여백이 없습니다.
<head>
<style> body { color: red; margin: 5px } </style>
</head>
<body>
<script>
let computedStyle = getComputedStyle(document.body);
// now we can read the margin and the color from it
alert( computedStyle.marginTop ); // 5px
alert( computedStyle.color ); // rgb(255, 0, 0)
</script>
</body>
따라서 취득하는 요소의 폭/높이 또는 기타 속성을 포함하도록 JavaScript 코드를 수정했습니다.
window.onload = function() {
var test = document.getElementById("test");
test.addEventListener("click", select);
function select(e) {
var elementID = e.target.id;
var element = document.getElementById(elementID);
let computedStyle = getComputedStyle(element);
var width = computedStyle.width;
console.log(element);
console.log(width);
}
}
계산된 값 및 해결된 값
CSS에는 다음 두 가지 개념이 있습니다.
계산된 스타일 값은 CSS 캐스케이드의 결과로 모든 CSS 규칙과 CSS 상속이 적용된 후의 값입니다.높이: 1em 또는 글꼴 크기: 125%처럼 보일 수 있습니다.
해결된 스타일 값은 요소에 최종적으로 적용되는 값입니다.1em 또는 125%와 같은 값은 상대적입니다.브라우저는 계산된 값을 가져와 모든 단위를 고정 및 절대값으로 만듭니다(예: high:20px 또는 font-size:16px).지오메트리 특성의 경우 해결된 값은 width:50.5px와 같은 부동 소수점을 가질 수 있습니다.
오래 전에 계산된 값을 가져오기 위해 getComputedStyle이 생성되었지만 해결된 값이 훨씬 더 편리하다는 것을 알게 되었고 표준이 변경되었습니다.
따라서 현재 getComputedStyle은 실제로 속성의 해결된 값을 반환합니다.
주의사항:
getComputedStyle에는 전체 속성 이름이 필요합니다.
항상 padding Left, 높이 또는 폭과 같이 원하는 정확한 속성을 입력해야 합니다.그렇지 않으면 올바른 결과가 보장되지 않습니다.
예를 들어 padding Left/padding Top 속성이 있는 경우 getComputed Style(elem)에 대해 무엇을 얻어야 합니까?패딩?아무것도, 아니면 알려진 패딩에서 "생성"된 값일 수도 있나요?여기에는 표준적인 규칙이 없습니다.
다른 불일치가 있습니다.예를 들어 일부 브라우저(Chrome)는 다음 문서에 10px로 표시되고 일부 브라우저(Firefox)는 표시되지 않습니다.
<style>
body {
margin: 30px;
height: 900px;
}
</style>
<script>
let style = getComputedStyle(document.body);
alert(style.margin); // empty string in Firefox
</script>
자세한 것은, https://javascript.info/styles-and-classes 를 참조해 주세요.
element.offset폭 및 element.offset이전 투고에서 제시한 대로 높이가 적당합니다.
그러나 콘텐츠를 중앙에 배치하려면 더 나은 방법이 있습니다.xhtml strict DO3}PE를 사용하는 경우, 본문 태그에 여백:0,auto 속성 및 px의 필수 너비를 설정합니다.컨텐츠가 페이지 중앙에 정렬됩니다.
CSS가 div를 중앙에 배치하는 데 도움이 되는 것 같습니다...
<style>
.monitor {
position:fixed;/* ... absolute possible if on :root */
top:0;bottom:0;right:0;left:0;
visibility:hidden;
}
.wrapper {
width:200px;/* this is size range */
height:100px;
position:absolute;
left:50%;top:50%;
visibility:hidden;
}
.content {
position:absolute;
width: 100%;height:100%;
left:-50%;top:-50%;
visibility:visible;
}
</style>
<div class="monitor">
<div class="wrapper">
<div class="content">
... so you hav div 200px*100px on center ...
</div>
</div>
</div>
다음 코드를 사용할 수도 있습니다.
var divID = document.getElementById("divid");
var h = divID.style.pixelHeight;
유연성
에 표시하는 경우<div>
화면 중앙에 팝업 메시지가 표시되므로 크기를 읽을 필요가 없습니다.<div>
플렉스를 사용할 수 있습니다.
.box {
width: 50px;
height: 20px;
background: red;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
width: 100vw;
position: fixed; /* remove this in case there is no content under div (and remember to set body margins to 0)*/
}
<div class="container">
<div class="box">My div</div>
</div>
이를 위해 높은 유연성을 갖춘 유틸리티 기능을 만들었습니다.
export type Size = {width: number, height: number};
export enum GetSize_Method {
/** Includes: content, padding. Excludes: border, margin, scroll-bar (if it has one), "position:absolute" descendants. */
ClientSize = "ClientSize",
/** Includes: content, padding, border, margin, scroll-bar (if it has one). Excludes: "position:absolute" descendants. */
OffsetSize = "OffsetSize",
/** Includes: content, padding, border, margin, scroll-bar (if it has one), "position:absolute" descendants. Excludes: none. */
ScrollSize = "ScrollSize",
/** Same as ScrollSize, except that it's calculated after the element's css transforms are applied. */
BoundingClientRect = "BoundingClientRect",
/** Lets you specify the exact list of components you want to include in the size calculation. */
Custom = "Custom",
}
export type SizeComp = "content" | "padding" | "border" | "margin" | "scrollBar" | "posAbsDescendants";
export function GetSize(el: HTMLElement, method = GetSize_Method.ClientSize, custom_sizeComps?: SizeComp[]) {
let size: Size;
if (method == GetSize_Method.ClientSize) {
size = {width: el.clientWidth, height: el.clientHeight};
} else if (method == GetSize_Method.OffsetSize) {
size = {width: el.offsetWidth, height: el.offsetHeight};
} else if (method == GetSize_Method.ScrollSize) {
size = {width: el.scrollWidth, height: el.scrollHeight};
} else if (method == GetSize_Method.BoundingClientRect) {
const rect = el.getBoundingClientRect();
size = {width: rect.width, height: rect.height};
} else if (method == GetSize_Method.Custom) {
const style = window.getComputedStyle(el, null);
const styleProp = (name: string)=>parseFloat(style.getPropertyValue(name));
const padding = {w: styleProp("padding-left") + styleProp("padding-right"), h: styleProp("padding-top") + styleProp("padding-bottom")};
const base = {w: el.clientWidth - padding.w, h: el.clientHeight - padding.h};
const border = {w: styleProp("border-left") + styleProp("border-right"), h: styleProp("border-top") + styleProp("border-bottom")};
const margin = {w: styleProp("margin-left") + styleProp("margin-right"), h: styleProp("margin-top") + styleProp("margin-bottom")};
const scrollBar = {w: (el.offsetWidth - el.clientWidth) - border.w - margin.w, h: (el.offsetHeight - el.clientHeight) - border.h - margin.h};
const posAbsDescendants = {w: el.scrollWidth - el.offsetWidth, h: el.scrollHeight - el.offsetHeight};
const sc = (name: SizeComp, valIfEnabled: number)=>custom_sizeComps.includes(name) ? valIfEnabled : 0;
size = {
width: sc("content", base.w) + sc("padding", padding.w) + sc("border", border.w)
+ sc("margin", margin.w) + sc("scrollBar", scrollBar.w) + sc("posAbsDescendants", posAbsDescendants.w),
height: sc("content", base.h) + sc("padding", padding.h) + sc("border", border.h)
+ sc("margin", margin.h) + sc("scrollBar", scrollBar.h) + sc("posAbsDescendants", posAbsDescendants.h),
};
}
return size;
}
사용방법:
const el = document.querySelector(".my-element");
console.log("Size:", GetSize(el, "ClientSize"));
console.log("Size:", GetSize(el, "Custom", ["content", "padding", "border"]));
나한테 효과가 있었던 건 이것뿐이었어
element.clientWidth -
parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-left")) -
parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-right"))
offsetWidth가 0을 반환하는 경우 요소의 스타일 너비 속성을 가져와 숫자를 검색할 수 있습니다.'100px' -> 100
/\d*/.exec(MyElement.style).폭)
다음은 특정 돔 요소의 높이를 결정하는 WKWebView 코드입니다(페이지 전체에서 제대로 작동하지 않음).
let html = "<body><span id=\"spanEl\" style=\"font-family: '\(taskFont.fontName)'; font-size: \(taskFont.pointSize - 4.0)pt; color: rgb(\(red), \(blue), \(green))\">\(textValue)</span></body>"
webView.navigationDelegate = self
webView.loadHTMLString(taskHTML, baseURL: nil)
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("document.getElementById(\"spanEl\").getBoundingClientRect().height;") { [weak self] (response, error) in
if let nValue = response as? NSNumber {
}
}
}
다음과 같이 width param을 사용합니다.
style={{
width: "80%",
paddingLeft: 100,
paddingRight: 200,
paddingTop: 30,
paddingBottom: 30,
border: "3px solid lightGray",
}}
언급URL : https://stackoverflow.com/questions/294250/how-do-i-retrieve-an-html-elements-actual-width-and-height
'programing' 카테고리의 다른 글
python datetime을 읽을 수 있는 형식의 날짜를 가진 문자열로 변환하려면 어떻게 해야 합니까? (0) | 2022.10.05 |
---|---|
치명적 오류: 최대 실행 시간 300초를 초과했습니다. (0) | 2022.10.05 |
jQuery를 사용하여 쿠키를 설정/해제하려면 어떻게 해야 합니까? (0) | 2022.10.05 |
MySQL IN 조건 제한 (0) | 2022.10.05 |
x86, arm, GCC 및 icc에서 작동하는 Linux에서 원자적인 작업을 수행하는 방법은 무엇입니까? (0) | 2022.10.05 |