How to change Background by clicking a button?

2019-08-02 06:13发布

问题:

I use Ionic 3. How to make my button change the image of my background by clicking?

This is my button.

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

And this is the background that is already installed on my page.

 #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');
          }
<div id="back" class="ion-content"> </div>

回答1:

Use [style.background]:

(I created demo: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(component)

image:any;

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

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

TO your comment:

integrate an id for my second background

use attr.id:

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

TS(component)

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

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


回答2:

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