How to make background images clickable (javascript or css)

ぐ巨炮叔叔 提交于 2019-12-22 13:57:09

问题


Please take a look this fiddle

How to make the background image clickable? When click "Take the survey" will go to a new page.

<div style="height:300px;width:300px;border-style:solid;border-width:5px;background-image:url('http://cdn.survey.io/embed/1.0/right_top_blue.png'); background-repeat:no-repeat;background-position:right top;">

By default, the background-image property repeats an image both horizontally and vertically.

</div>

Javascript or CSS are all preferred.

Edit: I don't want to use image float to right corner.


回答1:


You shouldn't.

What if a user has styles turned off, or is using a screen reader? They should be able to take the survey as well.

div{position:relative;}
a {display:block; width:120px; height:120px;
    position:absolute;
    top:0; right:0;
    text-indent:-9999px;

    background-image:url('http://cdn.survey.io/embed/1.0/right_top_blue.png'); 
    background-repeat:no-repeat;background-position:right top;}

Demo




回答2:


that's a simple example using position relative + absolute

http://jsfiddle.net/RZWCS/

you could also think to absolute positioning the link and use that image as link background (the text of the link could be the same appearing on the image and moved outside with negative text-indent or similar techniques)




回答3:


Check here for more info: http://bluedogwebservices.com/css-trick-turning-a-background-image-into-a-clickable-link/

Also, you could make the div relative, then just put image wrapped with anchor and position it absolutely in top right corner.

Edit

Html

<div class="wrapper">
<a href="/"><img src="yoursrc" alt="description"/></a>
<p>Some other text regularly positioned.</p>
<div>

CSS:

.wrapper
{
position:relative;
width:500px;
height:500px;
}

.wrapper a
{
position:absolute;
top:0px;
right:0px;
}



回答4:


I could be wrong here, but I don't think that CSS backgrounds can have events bound to them. I would personally cover it with a transparent div, or use a real image to tap into the events of the DOM element.

I would be interested if someone had a way to do this :)




回答5:


Just turn the div into an <a> element?

<a href="mysite.com" 
    style="display: block; 
    height:300px; 
    width:300px;
    border: 5px solid;
    background: url('http://cdn.survey.io/embed/1.0/right_top_blue.png') right top no-repeat;">
<a/>


来源:https://stackoverflow.com/questions/8811311/how-to-make-background-images-clickable-javascript-or-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!