【问题标题】:Expand hover area while keeping background color在保持背景颜色的同时扩大悬停区域
【发布时间】:2015-07-19 15:24:14
【问题描述】:

我有一个要扩展“悬停区域”的 div。 (如果您的鼠标刚好在元素之外,css :hover 选择器应该仍然有效。)

我尝试创建透明边框:(border:10px solid transparent;) 不幸的是,我的 div 有背景颜色,并且背景“泄漏”到了边框区域。 (有关问题的演示,请参阅 fiddle。)

我也尝试使用outline 代替边框,但是当涉及到悬停时,轮廓似乎并没有“计入”元素的一部分。 (看起来不错,但不会检测到额外的悬停区域。)

有没有办法用纯 CSS 来做到这一点(最好不要太多额外的元素)?如果没有,有没有使用 vanilla JS 的简单方法(no jQuery)?

$("#toggle").click(function(){
    $("#attempt").toggleClass("border");
});
#attempt {
    width:100px;
    height:200px;
    background:#aaa;
    margin:50px;
}

#attempt.border {
    margin:20px; /* Change margin to keep box in same place after border adds size */
    border:30px solid transparent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<div id="attempt"></div>
<button id="toggle">Toggle Border</button>
<p>Border (in the ideal case) would not change the element's background. However, adding the 30px border (even when transparent), will cause the background to change size.</p>

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    您只需要box-sizing 属性来防止背景泄漏。这是一个非常重要的。只需将其添加到#attempt

    #attempt {
      box-sizing: border-box;
    }
    

    查看更新的小提琴here。你可以了解更多关于box-sizinghere的信息。

    【讨论】:

    • 正是我想要的!感谢您的帮助!
    猜你喜欢
    • 2015-11-09
    • 2013-10-04
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多