gpt4 book ai didi

javascript - 在保持背景颜色的同时扩大悬停区域

转载 作者:行者123 更新时间:2023-11-28 16:59:41 25 4
gpt4 key购买 nike

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

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

我也尝试过使用 outline 而不是 border,但是当涉及到悬停时,outline 似乎并不“算作”元素的一部分。 (它看起来不错,但不会检测到额外的悬停区域。)

有没有办法用纯 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>

最佳答案

防止背景泄漏所需要做的就是 box-sizing 属性。这是一个非常重要的。只需将其添加到 #attempt 即可:

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

查看更新的 fiddle here .您可以了解有关 box-sizing 的更多信息 here .

关于javascript - 在保持背景颜色的同时扩大悬停区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31502782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com