Can you layer pictures on top of each other on a webpage?

后端 未结 7 1966
再見小時候
再見小時候 2020-12-23 23:34

I want to build a website that is a \"dress up\" game where you can click on different accessories and they will layer on top of each other.

Because it\'s a little d

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 23:59

    The short answer is yes.

    There are many ways of handling this. With HTML/CSS you can throw elements on top of each other easily.

    HTML:

    
    
    
    

    CSS:

    img
    {
        position:absolute;
        top: 0px;
        left: 0px;
    }
    

    So let's take a look at what's important here. You have 3 images in your HTML document (imga, imgb, and imgc). In order to overlay these, you have to first set their position to absolute so that the images will ignore any default layout behaviors. Then, you can use the left and top property to define the x,y coordinates of the img elements, respectively. In the example above, all of the elements are overlayed in the top-left corner of the page. In order control which image ends up on top, you can use the z-index property like so:

    #imga
    {
    z-index: 10;
    }
    
    #imgb
    {
    z-index: 20;
    }
    
    #imgc
    {
    z-index: 30;
    }
    

    This will make imgc appear in front, imgb appear behind imgc, and imga behind everything else. The z-index property assigns which element goes in front of another. The element with the greatest z-index goes on top, followed by the second greatest and so on.

    For your project, we can slightly tweak the code above:

    HTML

    
    
    
    

    CSS

    img
    {
    position:absolute;
    top: 0px;
    left: 0px;
    }
    #layer1
    {
       z-index: 10;
    }
    #layer2
    {
    z-index: 20;
    }
    
    #layer3
    {
    z-index: 30;
    }
    

    Since you now understand what lies where, you know that layer3 is on top (accessories layer), layer2 is in the middle (your person). and layer1 is on the bottom (the background). Then you can create accessories like so:

    
    

    And then using javascript, you can set the first layer's src equal to the clicked accessory's.

    function setAccessory(path){
         document.getElementById('layer1').src = path;
         //if you're using jQuery, $("#layer1").attr("src", path);
    }
    

    You can create as many accessories as you want. Say you want to add more accessories on top of your person, then you can easily create more layers, assign their z-indexes (and even do this dynamically using javascript, how exciting!)

    In conclusion, I hope you found this little tutorial useful. For your purposes, I suggest taking a look at jQuery as well as the element. They will be fun to use and certainly help your application.

    Good Luck with your application.

提交回复
热议问题