So as I am doing more and more web development I spend a lot of time looking at the markup on other people's pa开发者_StackOverflow社区ges. One thing that I have been tossing around is using anchors versus divs. Here is an example.
So I have some markup like this
<ul>
<li>
<div>
<input type="hidden" value="#"/>
div
</div>
</li>
<li>
<a href="#">anchor</a>
</li>
</ul>
In the first instance I have a div with a hidden field that could contain a url to go to or a value to use in javascript. The next way is the same thing only I am using an anchor instead.
My css looks like this:
li {
text-align:center;
padding-bottom:5px;
}
div, a {
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
padding:2px 5px;
}
div {
background: #aaa;
color:#fff;
}
div:hover {
cursor:pointer;
}
a{
background: #777;
display:block;
text-decoration:none;
color:#fff;
}
and my javascript looks like this:
$(function() {
$('div, a').click(function(e) {
e.preventDefault();
alert('clicked');
});
});
I have seen many pages that go for the first route with the div and use javascript to set the windows location via a hidden field. Is that correct or am I correct when I set the anchor's style to block?
Also, on another semi-related note, instead of nesting an image inside an anchor to make an image link, I have started taking a different approach. I set the anchor to block, set a width and a height, and then set the background image. Is this approach correct and safe across all browsers?
Thanks
In general, anchors are used to jump the browser window to a specific part of the page, like so:
http://www.example.com/#article-comments
There is a definite target for the anchor tag, so one should be used.
On the other hand, if you have a mail button:
<div id="mail">Email</div>
You're not going to browse to the URL and expect the button to automatically trigger (it might, but that shouldn't be something you'd expect to happen). Most of the buttons and links in Gmail's interface are in fact <div>
s, as anchors wouldn't be appropriate.
精彩评论