如何在Ionic中使元素的高度等于其宽度?

kor*_*737 6 javascript css angularjs angularjs-directive ionic

我正在制作一个带有Ionic的应用程序,我想要一个方形图像作为背景.需要根据不同的分辨率缩放图像; 我希望它能够填充设备的宽度,然后在保持宽高比的同时保持高度.

我已经尝试添加一个指令,以便计算正确的高度来设置,但我不能让它做任何事情,它似乎根本没有被调用.

HTML

<ion-view view-title="Home" >
  <ion-content class >
    <div  id = "card"  ng-model = "card">
      <h3>{{card.name}}</h3>

    </div>
  </ion-content>
</ion-view>
Run Code Online (Sandbox Code Playgroud)

CSS

#card{
    background-image: url("/img/education.png");
    background-size:  100% 100%;
    width : 100%;
}
Run Code Online (Sandbox Code Playgroud)

Javascript(controllers.js)

.directive("card", function($scope) {
   console.log("Card directive called.");
   return {
        restrict: "E",
        link: function (scope, element) {
            console.log("Link Called");
            element.height = element.width;
        }
   }
})
Run Code Online (Sandbox Code Playgroud)

Bre*_*ody 5

背景图像不会像那样定义元素的大小<img>。您有2个选择:

  1. 使用<img>元素代替background-image。这将导致元素调整为图像的大小(假设图像为正方形)。

  2. 使用一些棘手的CSS。假设您希望.square元素为其父元素宽度的50%。将其分配为的宽度50%,高度为0,填充底部为50%

    .square {
      width:50%;
      height:0px;
      padding-bottom:50%;
      background-size:  100% 100%;
    }
    
    Run Code Online (Sandbox Code Playgroud)

这是一个演示

  • 这也适用于任何长宽比,在上面的示例中将padding-bottom设置为25%将使椭圆形的宽度变为宽度的一半:-) (2认同)