gpt4 book ai didi

javascript - 当在 Javascript 中定义为百分比时,获取节点/元素的正确宽度和高度

转载 作者:行者123 更新时间:2023-12-03 03:11:27 25 4
gpt4 key购买 nike

使用 getBoundingClientRect 解决;感谢snapjs的评论

<小时/>

我想做一个类似于 https://codepen.io/joshhunt18/pen/NPKEzQ 的裁剪器.

在我的例子中,裁剪器在加载图像后以模式打开。因为图像可以有不同的比例,所以我想将图像宽度和高度更改为位于 modal_area 内。

我的问题是,在 JavaScript 中,当我尝试获取 model_area(图像容器)的宽度和高度时,如果以百分比定义,我无法获得真实的宽度/高度。我认为是采用父宽度和高度。

.modal {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1050;
display: none;
overflow: hidden;
outline: 0;
}


.modal-area {
position: absolute;
top: 50%;
left: 50%;
width: 50%;
height: 50%;
transform: translate(-50%, -50%);
margin: 0 auto;
padding: 30px;
background-color: blue;
border-radius: 4px;
box-shadow: 0 0 50px black;
z-index: 20;
overflow: hidden;
}

Javascript:

function add_new_image(data, formset) {
var file = data.files[0];
var reader = new FileReader();
var modal_DOM_ref, modal_area_DOM_ref;
reader.onload = function (event) {
var img = new Image();
// ratio = img.width / img.height;
// get the modal and make visible
modal_DOM_ref = get_modal(formset);
modal_area_DOM_ref = get_modal_content(modal_DOM_ref);
make_modal_visible(modal_DOM_ref);
//check ratio width/height to see who is bigger
img.onload = function() {if( modal_area_DOM_ref.offsetWidth/img.width > modal_area_DOM_ref.offsetHeight/img.height){

img.style.width = img.width * (modal_area_DOM_ref.offsetWidth/img.width) + 'px';
img.style.height = img.height * (modal_area_DOM_ref.offsetWidth/img.width) + 'px';
}
else {
console.log('b',img.width, img.height, (modal_area_DOM_ref.offsetHeight/img.height));
img.style.width = img.width * (modal_area_DOM_ref.offsetHeight/img.height) + 'px';

img.style.height = img.height * (modal_area_DOM_ref.offsetHeight/img.height) + 'px';
}}
img.src = event.target.result;
// add the image
modal_area_DOM_ref.appendChild(img);

};
reader.readAsDataURL(file);
}

最佳答案

style 属性与 style 属性映射。

var elem = document.getElementById('B');

// without border height
console.log('clientWidth: ' + elem.clientWidth);
console.log('clientHeight: ' + elem.clientHeight);

// with border height
console.log('offsetWidth: ' + elem.offsetWidth);
console.log('offsetHeight: ' + elem.offsetHeight);
div{
border: 3px solid black;
}

div#A{
width: 500px;
height: 500px;
}

div#B{
width: 30%;
height: 46%;
}
<div id="A">
<div id="B"></div>
</div>

关于javascript - 当在 Javascript 中定义为百分比时,获取节点/元素的正确宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46932419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com