2015-07-19 61 views
1

我有一個div,我想擴大「懸停區域」。 (如果你的鼠標就在元素外面,css:hover選擇器應該仍然有效。)展開懸停區域,同時保持背景顏色

我試着創建一個透明邊框:(border:10px solid transparent;)不幸的是,我的div有背景色,背景爲「泄漏「到邊界地區。 (請參閱fiddle進行演示。)

我也嘗試使用outline而不是邊框​​,但輪廓在懸停時似乎不是「元素」的一部分。 (它看起來是正確的,但不會檢測到額外的懸停區域。)

有沒有辦法用普通的CSS來做到這一點(最好沒有多餘的元素)?如果沒有,是否有一個簡單的方法使用香草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>

回答

1

所有你需要防止的背景泄漏是box-sizing財產。這是非常重要的一個。只需將它添加到#attempt

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

退房更新的小提琴here。你可以瞭解更多關於box-sizinghere

+1

正是我在找的東西!謝謝您的幫助! – PullJosh