我想这样做,以便可以点击整个div,并在没有JavaScript和有效代码/标记的情况下点击链接到另一个页面.
如果我有这个我想要的结果 -
<a href="#">
<div>This is a link</div>
</a>
Run Code Online (Sandbox Code Playgroud)
W3C验证器说块元素不应放在内联元素中.有一个更好的方法吗?
Mar*_*rio 146
可以使链接填充整个div,这样可以使div可以点击.
CSS:
#my-div {
background-color: #f00;
width: 200px;
height: 200px;
}
a.fill-div {
display: block;
height: 100%;
width: 100%;
text-decoration: none;
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<div id="my-div">
<a href="#" class="fill-div"></a>
</div>
Run Code Online (Sandbox Code Playgroud)
Ale*_*ffe 86
当没有javascript和有效代码点击时,整个div链接到另一个页面,这可能吗?
迂腐的回答:没有.
由于您已经提出了另一条评论,因此div在a标记内嵌套是无效的.
但是,没有什么能阻止您使a标记的行为与a非常相似div,除了您不能在其中嵌套其他块标记.如果它适合您的标记,请display:block在您的a标签上设置并按照您喜欢的尺寸/浮动它.
如果你违背了你的问题的前提,你需要避免使用javascript,正如其他人指出的那样,你可以使用onClick事件处理程序.jQuery是一个流行的选择,使这个易于维护.
Jam*_*imi 82
<div onclick="location.href='#';" style="cursor: pointer;">
</div>
Run Code Online (Sandbox Code Playgroud)
Sin*_*dem 22
没有JS,我这样做:
我的HTML:
<div class="container">
<div class="sometext">Some text here</div>
<div class="someothertext">Some other text here</div>
<a href="#" class="mylink">text of my link</a>
</div>
Run Code Online (Sandbox Code Playgroud)
我的CSS:
.container{
position: relative;
}
.container.a{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
text-indent: -9999px; //these two lines are to hide my actual link text.
overflow: hidden; //these two lines are to hide my actual link text.
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*ohn 10
我没有JavaScript /图像的解决方案.只使用CSS.它适用于所有浏览器.
HTML:
<a class="add_to_cart" href="https://www.redracingparts.com" title="Add to Cart!">
buy now<br />free shipping<br />no further costs
</a>
Run Code Online (Sandbox Code Playgroud)
CSS:
.add_to_cart:hover {
background-color:#FF9933;
text-decoration:none;
color:#FFFFFF;
}
.add_to_cart {
cursor:pointer;
background-color:#EC5500;
display:block;
text-align:center;
margin-top:8px;
width:90px;
height:31px;
border-radius:5px;
border-width:1px;
border-style:solid;
border-color:#E70000;
}
Run Code Online (Sandbox Code Playgroud)
在HTML5中,嵌套块级别元素在锚点中不再无效.请参阅http://html5doctor.com/block-level-links-in-html-5/和http://www.w3.org/TR/html5/the-a-element.html.我不是说你应该使用它,但在HTML5中它可以使用.<a href="#"><div></div></a>
接受的答案是最好的答案.像其他建议一样使用JavaScript也很糟糕,因为它会使"链接" 无法访问(对于没有JavaScript的用户,包括搜索引擎和其他用户).
jQuery将允许您执行此操作。
查找click()功能:http :
//api.jquery.com/click/
例:
$('#yourDIV').click(function() {
alert('You clicked the DIV.');
});
Run Code Online (Sandbox Code Playgroud)