如何通过单击按钮更改背景?

时间:2018-06-18 09:54:40

标签: html css button ionic-framework background

我使用Ionic 3。 如何通过单击?

使我的按钮更改我的背景图像

这是我的按钮。

action items

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

<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');
          }

2 个答案:

答案 0 :(得分:0)

使用[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";
}

答案 1 :(得分:0)

Ionic uses Angular under the hood. So best way to handle the event is in controller of your view. So in your 'YourController.ts' file you need to write handler method like this:

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

Then you can use this event in your button like this:

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

Above is simple angular way of binding event to handler method. Now we can use Angular attribute binding to bind style attribute to 'image' property like this:

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

So basically when user will click your button then following things will happen:

  1. changeBackground() method of YourController.ts will be called.
  2. Here we are setting property image to new value.
  3. So DOM manipulation of Angular will change div background to this new value.
  4. New image replaces existing image.

To all those who are still wondering why Angular is being used here can watch this: Ionic Intro and Crash course