【问题标题】:How to change Background by clicking a button?如何通过单击按钮更改背景?
【发布时间】:2018-11-27 03:28:07
【问题描述】:

我使用 Ionic 3。 如何让我的按钮通过点击改变我的背景图片?

这是我的按钮。

<button id="transparent" ion-button round color="light"> </button>

这是我页面上已经安装的背景。

 #back {
            background-size: 100%;
            background-repeat: no-repeat;
            background-size: cover;
            width: 105vw;
            height: 100vh;
            margin-left: -10%;
            background-attachment: fixed;
            margin-top: -10%;
            background-position: center center;
          }
          
          .ion-content {
            background: url('myurl');
          }
&lt;div id="back" class="ion-content"&gt; &lt;/div&gt;

【问题讨论】:

  • 你用的是angular还是javascript
  • @לבנימלכה — 问题带有 ionic-framework 标签
  • @Quentin ionic-framework 与 angular 一起使用...我说的对吗?

标签: html css button ionic-framework background


【解决方案1】:

使用[style.background]:

(我创建了演示:https://stackblitz.com/edit/ionic-mgbhjq?file=pages%2Fhome%2Fhome.html

<div id="back" class="ion-content" [style.background]="'url('+image+')'"></div>
<button id="transparent" ion-button round color="light" (click)="changeImage()"> </button>

TS(组件)

image:any;

ngOnInit(){
this.image ="your first url";
}

changeImage(){
this.image="your second url";
}

您的评论:

为我的第二个背景整合一个 id

使用attr.id:

<div  attr.id="idParam" class="ion-content" [style.background]="'url('+image+')'"></div>

TS(组件)

image:any;
idParam:string="back";
ngOnInit(){
this.image ="your first url";
}

changeImage(){
this.image="your second url";
this.idParam="secondBack";
}

【讨论】:

【解决方案2】:

Ionic 在后台使用 Angular。因此,处理事件的最佳方法是在您的视图控制器中。因此,在您的“YourController.ts”文件中,您需要编写如下处理程序方法:

changeBackground() {
    this.image = '<url_of_new_image>';
}

然后你可以像这样在你的按钮中使用这个事件:

<button id="transparent" ion-button round color="light" (click)="changeBackground()"> </button>

以上是将事件绑定到处理程序方法的简单角度方式。现在我们可以使用 Angular 属性绑定来将样式属性绑定到 'image' 属性,如下所示:

<div id="back" class="ion-content" [style.background]="'url('+image+')'"></div>

所以基本上当用户点击你的按钮时,会发生以下事情:

  1. 将调用YourController.ts的changeBackground()方法。
  2. 在这里,我们将属性 image 设置为新值。
  3. 因此 Angular 的 DOM 操作会将 div 背景更改为这个新值。
  4. 新图片替换现有图片。

对于那些仍然想知道为什么在这里使用 Angular 的人可以观看: Ionic Intro and Crash course

【讨论】:

  • 好的!我看了看。你的回答很好,我的回答很全面。
猜你喜欢
  • 2023-03-15
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多