add hyperlink to an image(background image)
I'm a bit lost as to how to add a hyperlink to an image(background image) that is being called into the page with this HTML below:
<div style="background-color: #fff; background: #fff url(/affiliat开发者_开发知识库e/uploads/images/subs_bg_4e1a7912cf9a79.22853644.jpg) no-repeat right top" class="bigshadow" id="wrapper"></div>
i need to add a hyper-link into the background image.
$("#wrapper").click(function(){here goes redirect}) Or u just need background-image: ??
$('#wrapper').live('click',function(){
location.href = "http://www.yoursite.com";
});
i'd use live() since your question implies that the div is added to the page dynamically.
if you really want to insert hyperlink (a element) you could do:
$('#wrapper').append($('<a/>',{'html':'<br/>','href':'http://www.yoursite.com'}).css({'display':'block','height':'100%','width':'100%'}));
you maybe want to run all that on the class instead of id so it works for multiple elements
Put a link inside your div with display:block
like this: (this trick works even in ie6,7,8)
html:
<div style="background-color: #fff; background: #fff url(img.jpg) no-repeat right top" class="bigshadow" id="wrapper">
<a title="click here" href="http://mysite.com"><span>MySite.com</span></a>
</div>
css:
#wrapper a {
display: block;
height: 101px;
width: 100%;
}
jsFiddle example.
I don't understand why it has to be a <div>
with a background-image... that just means that you'll be in agony city trying to force the browser to do something because of improper use of markup.
It's unclear from your question as to whether you have control over the source of that <div>
.
If you do have control over what creates that <div>
, I would recommend changing it to an <img src="pathtotheimage.jpg"/>
and wrapping it in an anchor (<a>
) tag:
If you have no control over the creation of the <div>
, then I suggest extracting the image URL out of it and employing proper semantic markup anyway.
In either case, here's the markup you should be aiming for:
<a href="#" id="wrapper" class="bigshadow">
<img src="/affiliate/uploads/images/subs_bg_4e1a7912cf9a79.22853644.jpg" />
</a>
Doing it this way, you require no additional CSS to achieve what you want -- a clickable image.
If you need to extract the image URL out of the response, then do this:
function extractImageUrl(html) {
return $(html).css('background-image').replace(/url\(\"(.*?)\"\)/, "$1");
}
精彩评论