【问题标题】:AngularJS set element fixed position based on another elementAngularJS根据另一个元素设置元素固定位置
【发布时间】:2014-05-21 09:48:06
【问题描述】:

此应用拍摄一张图片,这是必不可少的背景或工作区。我需要在给定特定坐标(顶部、左侧、宽度、高度)的情况下将输入文本字段添加到此工作区。这些坐标将相对于图像(上/左 = 0/0)。我将如何相对于图像定位我的字段/元素?

        <img id="background" ng-src="{{page.backgroundImage}}" />
        <input type="text" ng-repeat="field in page.fields" ng-model="field.value" 
               ng-style="{position:'absolute',
                              left:field.left,
                               top:field.top,
                             width:field.width,
                            height:field.height}"/>

上面的代码非常适合绝对定位,但它与图像无关。

【问题讨论】:

  • 你可以使用 ng-class 来动态添加/删除类,如果你想直接绑定到样式值也可以使用 ng-style
  • 这很好用,但我仍然有如何设置相对于其他元素的位置的问题。
  • 你不能把 img 和 input 的列表都包装到一个具有相对位置的 div 中吗?那么输入的绝对位置将基于div?
  • 我为整个页面添加了代码,以便您查看上下文。将其包装在相对位置 div 中没有任何作用。图像在正确的位置,它显示在图像之外的输入框。
  • 图像应该填充 div,输入将相对于 div,因此相对于图像。如果您打算仅使用 CSS 解决它,我建议使用静态内容(无角度)处理它,然后插入模型中的 ng 样式值。通过 fiddle 或 plnkr 的示例也会有所帮助。

标签: css angularjs angularjs-directive


【解决方案1】:
<div style="position:relative">
    <img id="background" ng-src="{{page.backgroundImage}}" class="course-image" />
    <input type="text" ng-repeat="field in page.fields" ng-model="field.value"
           style="position:absolute"
           ng-style="{left:field.left,
                       top:field.top,
                     width:field.width,
                    height:field.height}" />       
</div>

【讨论】:

  • 请注意:最好不要在ngStyle 指令中包含常量值(例如position: 'absolute')。这会导致每个摘要循环的额外评估(并且有几个一直在进行)。由于它总是会计算为相同的值,只需将其硬编码到 style 属性中即可。
  • 只是你的回答中的一点。属性样式需要是常见的 html 样式,例如:style="position: absolute"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多