div边框可灵活调整大小,内部带有绝对定位的图像,纯CSS / JavaScript

时间:2019-05-19 15:46:13

标签: javascript html css

我正在创建一个动画图像编辑器。有些图片是最顶层的,有些则需要放在div中,并具有绝对位置。 “应该工作”下面的代码?它有一个错误,您知道它是什么吗?

仅供参考-以下文字是为了满足问题的需要,而不是上面的文字。所以,请允许我用它来问一个补充问题。总的来说,我发现在边界上存在问题,例如:    element.style.border =“ 1px纯红色”,似乎给我带来了问题,或者:  element.style =“ border:1px纯红色”。这两个都应该工作吗?

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test</title>
<style type="text/css">
.item {
  position: absolute;
  height: auto;
  opacity: 1;
}

.mouseover { border:1px dashed green; }

</style>
<script>
function id(name) { return document.getElementById(name); }
function fixBorder() {
    var w1 = id("part-1").style.width.replace("px", "");
    var h1 = id("part-1").style.height.replace("px", ""); 
  var l1 = id("part-1").style.left.replace("px", "");
  var t1 = id("part-1").style.top.replace("px", "");

    var w2 = id("part-2").style.width.replace("px", "");
  var h2 = id("part-2").style.height.replace("px", ""); 
  var l1 = id("part-2").style.left.replace("px", "");
  var t1 = id("part-2").style.top.replace("px", "");

  // "math" for the group size and position
  var wOverlay = l2 - w1;
  var hOverlay = t2 - h1;

  var wg = w1 + w2 - wOverlay;
  var hg = h1 + h2 - hOverlay;

  var lg = ( l1 < l2 ) ? l1 : l2;
  var tg = ( h1 < h2 ) ? h1 : h2;

  // ok, now how to I apply that math? is it easy? 
    id('group').onmouseover = function(event) {  
      alert("on mouseover");
    if (! event.shiftKey) elem.classList.add('mouseover'); 
    else elem.classList.remove('mouseover');
  }

  id('group').style.left = lg + "px";
  id('group').style.top = hg + "px";

  id('group').style.width =  width + "px";
  id('group').style.height = height + "px";

</script>
</head>
<body>
<div id="group" style="border:5px solid red">
  <img id="part-1" class="item" src="https://dummyimage.com/640x4:3/"> 
  <img id="part-2" class="item" src="https://dummyimage.com/300/09f.png/fff">  
 </div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

position: absolute;height: auto;的样式会破坏布局,请尝试将其删除,以使边框遍及您的父项

您要为所有item设置绝对位置,从而将所有div置于左上角的class="item"位置,并且不指定高度。您的图片显示为大于实际的div,因为它们溢出了div。但是div本身没有设置height,这就是为什么只看到边框被压缩的原因

<!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Test</title>
    <style type="text/css">
    .item {
      /*position: absolute;*/
      /*height: auto;*/
      opacity: 1;
    }
    </style>
    <script>
    
    </script>
    </head>
    <body>
    <div id="group" class="item" style="border:5px solid green">
      <img id="group-1" class="item" src="https://dummyimage.com/640x4:3/"> 
      <img id="group-2" class="item" src="https://dummyimage.com/300/09f.png/fff">  
     </div>
    </body>
    </html>