简体   繁体   中英

Slide background image ReactJS | CSS

I have a horizontal image that I want to use as a background. I want to change the position of the image depending on the argument passed to the function. My image:

在此处输入图片说明

My code so far:

import React, { Component } from 'react'

import Background from '../images/background_image.jpg';

class MoveImage extends Component{

    constructor(props) {
    super(props);
    this.state = {
      counter: 1
     }
  }

    const bgSlide = {
        backgroundImage: `url(${Background})`
    };

    moveBGImage=(id)=>{
        //slide the image depending on the id
        //so if id=2, the image should slide from screen1 to screen2
    }

    render(){
        return(
            <div style = { bgSlide } >

                <button
                    onClick = this.moveBGImage(this.state.counter+1)
                >
                    Click Me

                </button>

            </div>

            )
    }


}


export default MoveImage;

So if the counter is 2, I want to show screen2 part of the image. And screen1 should slide left and screen2 slide in from right. Can this be done in React?

It's possible with CSS background-position :

 const App = () => { const [screen, setScreen] = React.useState(1) const toggleScreen = () => setScreen(s => s > 3 ? 1 : s + 1) return ( <div className={`screen nr${screen}`} onClick={toggleScreen} /> ) } ReactDOM.render(<App /> , document.getElementById('root')) 
 .screen { background: url('https://i.stack.imgur.com/72bFV.png') no-repeat 0 0; background-size: cover; width: 120px; height: 100px; transition: 300ms; } .screen.nr2 { background-position: 33.33% 0; } .screen.nr3 { background-position: 66.67% 0; } .screen.nr4 { background-position: 100% 0; } 
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script> 

Note: I used the image from question, which does not have exact 1/4 parts, so the red lines do not align exactly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM