在保持背景颜色的同时展开悬停区域

时间:2015-07-19 15:24:14

标签: javascript jquery css

我有一个div,我想扩展"悬停区域"的。 (如果您的鼠标位于元素之外,则css:hover选择器应该仍然有效。)

我尝试创建一个透明边框:( border:10px solid transparent;)不幸的是,我的div有背景颜色,背景"泄露"进入边境地区。 (有关此问题的说明,请参阅fiddle。)

我也尝试使用outline代替边框,但大纲似乎没有" count"作为悬停时元素的一部分。 (看起来不对,但是没有检测到额外的悬停区域。)

有没有办法用纯CSS(最好不是很多额外的元素)做到这一点?如果没有,是否有一个简单的方法使用vanilla JS(没有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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

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

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

查看更新的小提琴here。您可以详细了解box-sizing here

相关问题