【问题标题】:Why isn't the div width/height changing after loading?为什么加载后 div 的宽度/高度没有变化?
【发布时间】:2017-09-10 08:47:08
【问题描述】:

我正在尝试创建一个在线图像裁剪器,用户可以在其中上传照片并显示一个可通过按钮更改的框(框架)。裁剪照片并将其发送回给用户。

我有一个基本的 php 表单上传器模板(工作)。然后它将图像显示在div 中,在其上方有另一个透明的div,并带有标记裁剪区域的边框。

divs 的初始值在页面发送给用户时通过 php 在 css 部分中设置。我正在尝试调整框架div 的大小,因为给定的宽度是框架的图像宽度+2 px(高度相同),它应该只是图像宽度(-2 px)。

这段代码应该可以工作,但是当弹出警报时,它们显示框架宽度/高度没有改变原始值,并且看起来框架没有改变。

<!DOCTYPE html>
<head>
<style type="text/css">
html, body {
    width: 500px;
    height: 334px;
    background-color: black;
}

.top {
    margin-top: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
    margin-right: 0px;
    width: 500px;
    height: 334px;
    position: absolute;
    background-color: transparent;
    border-width: 1px;
    border-style: solid;
    border-color: white;
    z-index: 999;
}

.bottom {
    top: 0px;
    left: 0px;
    position absolute;
    width: 500px;
    height: 334px;
    background-color: green;
//  background-image: url(uploads/1505002267.jpg);
    z-index: 998;
}
</style>

<script type="text/javascript">
function myOnLoad() {
    var w = 500;
    var h = 334;
    var frame = document.getElementsByClassName('top')[0];
    w = w - 2;
    h = h - 2;
    //frame.setAttribute("style", "width: " + w + "px;");
    //frame.setAttribute("style", "height: " + h + "px;");
    frame.style.width = w + "px;";
    frame.style.height = h + "px;";
    alert(frame.offsetWidth);
    alert(frame.offsetHeight);
}
</script>
<title>Test Website</title>
</head>
<body onload="myOnLoad()">
<div class="wrapper">
    <div class="bottom" id="image">
        <div class="top" id="frame">
        </div>
    </div>
</div>
</body>
</html>

我知道我可以更改 php 赋予 css 部分的值,但无论如何我都需要在下一步更改裁剪比例,所以我需要这种方式来工作。请帮忙,我一直在看这个代码太久了。

【问题讨论】:

    标签: javascript php html css


    【解决方案1】:

    去掉引号中的分号。

    frame.style.width = w + "px";
    frame.style.height = h + "px";
    

    另外,offsetHeightoffsetWidth 考虑了边界。由于您的边框宽度为 1px,因此它将图像的高度和宽度都增加了 2px,从而抵消了 2 的减法。

    在 MDN 上阅读有关偏移量 widthheight 的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 2018-09-20
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多