开发者

Is linking a <div> using javascript acceptable?

开发者 https://www.devze.com 2023-02-10 12:58 出处:网络
I want to link an entire <div>, but CSS2 does not support adding an href to a div (or span for that matter). My solution is to use the onClick property to add a link. Is this acceptable for mode

I want to link an entire <div>, but CSS2 does not support adding an href to a div (or span for that matter). My solution is to use the onClick property to add a link. Is this acceptable for modern browsers?

Example code:

<div class="frommage_box" id="about_frommage" onclick="location.href='#';">
            <div class="frommage_textbox" id="ft_1"><p>who is Hawk Design?</p></开发者_StackOverflowdiv>

My test page is at http://www.designbyhawk.com/pixel. Updated daily.

Thanks for the help.


You don't need to do that. There's a perfectly simple and standards-compliant way to do this.

Block-level elements will by default take up the entire available width. a elements are not by default block-level, but you can make them so with display: block in CSS.

See this example (no Javascript!). You can click anywhere in the div to access the link, even though the link text doesn't take up the whole width. You just need to remove that p element and make it an a.


Attaching a click event handler to a <div> element will work for your users with JavaScript enabled.

If you're looking for a progressive enhancement solution, however, you'll want to stick with a <a> element.


It is acceptable, only it's not good for SEO.

Maybe you can make a <a> element act like a div? (settings it's style to display:block etc.)


It will work in every browser(even IE6). The only problem with this is that search engines probably won't fetch it since it's javascript. I see no other way to be able to make an entire div click-able though. Putting an "a" tag around it won't work in all browsers.


If all you're trying to achieve is a large clickable box, try setting the following CSS on an anchor:

a {
   display: block;
   padding: 10px;
   width: 200px;
   height: 50px;
}


HTML:

<div class='frommage_box'>
    <a href='location.html'>CONTENT GOES HERE</a>
</div>

CSS:

.frommage_box a{
    display:block;
    height:100%;
}

By default block elements take up 100% width. We adjust the height to 100%. And this will allow spiders to crawl yoru page.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号