我正在编写一个网站,其中有一个代表相框的固定宽度 div。 用户可以更改框架的宽度和高度值,并使用 Jquery,我想向他们展示框架的表示形式。
框架 div 本身的宽度是固定的,因为在页面设计中它的空间有限。因此,唯一可以物理改变的维度是高度。
例如,如果用户指定了 300mm 的框架宽度和 200mm 的高度,我必须在屏幕上表示出来。我正在努力的是获得准确的表示。 目前,我正在执行以下操作:
$(function() {
$( "#artwork_height_input" ).change(function() {
//Work out the new proportional height (the width of the div is fixed, so only the height can be altered)
var divWidth = $( "#artwork_width_input" ).val();
var divHeight = $( "#artwork_height_input" ).val();
var ratio = divWidth / divHeight;
var newDivHeight = divHeight / ratio;
alert(newDivHeight);
$("#scaledimage").height(newDivHeight-2);
});
});
问题是,这会导致 newDivHeight 为 133.33,我知道这是不对的。 谁能帮我解决这个问题?我敢肯定它比 Jquery 更像是数学,但我们将不胜感激!
谢谢!
最佳答案
我认为你的数学有问题。
你说你的div是固定宽度的,所以我们需要确定他的高度。
用户指定的框架有一定的比例,我们需要这个等式成立。
DivHeiht/DivWidth = FrameHeight/FrameWidth
因此,DivHeight = DivWidth*(FrameHeight/Framewidth)
$(function() {
$( "#artwork_height_input" ).change(function() {
//Work out the new proportional height (the width of the div is fixed, so only the height can be altered)
var Framewidth= $("#artwork_width_input").val();
var FrameHeight= $("#artwork_height_input").val();
var DivWidth = $("#scaledimage").width();
var DivHeight = DivWidth*(FrameHeight/Framewidth);
//alert(DivHeight);
$("#scaledimage").height(DivHeight);//-2 for what?
});
});
或者:更短的方式:(但更难理解)
$(function() {
$( "#artwork_height_input" ).change(function() {
$("#scaledimage").height($("#scaledimage").width()*$("#artwork_width_input").val()/$("#artwork_height_input").val());});
});
关于jquery - 如何在固定宽度的div上设置div高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18979044/