Making part of an image clickable

2019-06-02 16:39发布

问题:

I have a background image applied this way

HTML

<div id="background">
    <img src="stock.png" class="stretch" alt="image" />
</div>

CSS

#background {
    width: 100%; 
    height: 100%; 
    position: absolute; 
    left: 0px; 
    top: 0px; 
    z-index: 0;
}

.stretch {
    width:100%;
    height:100%;
}

I want to have a part of an area of the image clickable, so that it will link me to the next page, any simple ways of doing this?

回答1:

You could always make a link relative and z-index it to the proper position:

<div id="background">
    <img src="stock.png" class="stretch" alt="image" />
    <a href="path/to/url/" class="link"></a>
</div>

Then something like:

#background {
    width: 100%; 
    height: 100%; 
    position: absolute; 
    left: 0px; 
    top: 0px; 
    z-index: 0;
}
.stretch {
    width:100%;
    height:100%;
    z-index:1;
}
.link {
    width:200px;
    height:200px;
    position:absolute;
    top:50%;
    left:50%;
    display:block;
    z-index:2;
}

Then move and style the link as you will with CSS and/or image(s).



回答2:

Well add another div with position: absolute; and then define his position with this

left:100px;
top:100px;


回答3:

I know this is an old question but in my opinion the simplest and best way to do this would be with an image map. They're pretty straight forward, basically you can define clickable shapes on an image (rectangles, circles, and even polygonal shapes but I've never used those). The coordinates and sizes of the shapes are all relative to the image so it is very flexible.

http://www.w3schools.com/tags/tag_map.asp explains how to use it.



标签: html css xhtml