jQuery(".my_container").hover(function(){
//do code
}, function(){
//do code
});
.my_container { width: 100px; height: 100px; margin: 50px; }
上面的代码对鼠标悬停在边距上没有反应(边距不是元素的一部分? - 我该如何更改它?
你可以使用 50px 的透明边框代替 - 边距实际上不应该是可鼠标的......
包含一个伪元素,例如
.my_container:before {
content:'';
position:absolute;
top:-50px;
bottom:-50px;
left:-50px;
right:-50px;
}
这会为现有元素的可点击区域添加额外的 50px。
如果您只想在触摸屏设备上添加此内容,则可以执行以下操作:
.touchevents .my_container:before {
...
}
这需要像 Modernizer 这样的东西来插入适当的基于功能的 CSS 类。
<小时 />更新
根据@Jaladh的评论,您可能还需要将position:relative
应用于容器元素,因为上面的position:absolute
将相对于具有position
属性的第一个祖先:
.my_container {
position:relative;
}
也许使用第二个包装器元素,在外部元素上填充,在内部元素上使用现有背景和填充样式:
<div class="my_container">
<div class="my_container_inner">
<!-- etc. -->
</div>
</div>
jQuery(".my_container").hover(function(){
//do code
}, function(){
//do code
});
.my_container { padding: 50px; }
.my_container_inner { width: 100px; height: 100px; /* etc. */ }
基于 @Dunc 的解决方案,您也可以使用伪元素来模拟容器,让实际容器的行为类似于边距。这将看起来像:
.my_container {
width: calc(100px + (2 * 50px));
height: calc(100px + (2* 50px));
position: relative;
}
.my_container::before {
content: '';
position: absolute;
top: 50px;
bottom: 50px;
left: 50px;
right: 50px;
}
还要确保将您在my_container
中的所有其他属性(如背景颜色、边框等)移动到my_container::before
before
因为它在这里就像我们的容器一样。
如果您的容器是网格项,并且您希望它们之间的间隙可悬停,这基本上很有用,因为否则在这种情况下使用 psuedo 元素添加边距将无法正常工作。
将边距更改为填充,它将是可悬停的。