2017-09-04 53 views
2

這OP知道,一個簡單的JavaScript click事件將很容易足以作爲替代這裏CSS ....但是好奇心渴望得到滿足:光標樣式忽略:重點以創建CSS切換

使用:focus僞類可以讓僞指令在激活時顯示pointer遊標?看一看。

body { 
 
    font-family: sans-serif; 
 
} 
 
div { 
 
    cursor: pointer; /* div should *Always* have a pointer cursor */ 
 
    width: 10rem; 
 
    height: 10rem; 
 
    background-color: #0dd; 
 
    transition-property: background-color; 
 
    transition-duration: 1s; 
 
} 
 
div:focus { /* Apply this only when div is focused/clicked */ 
 
    pointer-events: none; /* pointer-events disabled to allow toggle */ 
 
    background-color: #ee0; 
 
    outline: 0; 
 
}
<div tabindex="0"></div> <!-- tabindex allows div to be focused --> 
 
Please click the square<br>above. Again.

注意當DIV是黃色的指針光標更改回其默認的鼠標指針行爲?(移動鼠標非常輕微,如果事實並非如此)

我想防止光標改變。我希望光標始終保持在pointer狀態。

當div被點擊時觸發一個事件,但是同樣的按鈕不能被點擊或者重新聚焦似乎。所以點擊黃色div不會觸發事件恢復爲藍色,除非我們以某種方式欺騙瀏覽器認爲非常相同的點擊空間是外部 div以外的區域。這就是爲什麼pointer-events: none行存在。因此,切換可以一次又一次地激活,如切換應該。

我唯一的願望是以某種方式將指針光標保持在黃色div而不改變它的切換行爲。這可能是不可能的pointer-events: none但有沒有辦法做到這一點?某種類型的解決方法或破解?

+0

這是不可能的,至少在沒有JS。 – TricksfortheWeb

+0

@TricksfortheWeb我正在嘗試僞元素,似乎接近解決方案,但像你說我還沒有能夠實現它。如果不是使用'pointer-events',而是使用'z-index'來玩? – basement

+0

我不認爲'z-index'也可以工作,因爲在div上沒有任何點擊會被註冊。你試圖做的是反直覺的:你試圖阻止點擊的結果,但保持點擊的效果。唯一可行的方法是將透明的div直接放置在您定位的目標上。 – TricksfortheWeb

回答

1

你問的答案:

body { 
    font-family: sans-serif; 
} 
#wrap { 
    position: relative; 
    width: 10rem; 
    height: 10rem; 
} 
#top { 
    cursor: pointer; /* div should *Always* have a pointer cursor */ 
    background-color: #0dd; 
    transition-property: background-color; 
    transition-duration: 1s; 
    position: relative; 
    z-index: 100; 
    position: absolute; 
    width: 10rem; 
    height: 10rem; 
} 
#top:focus { /* Apply this only when div is focused */ 
    pointer-events: none; /* pointer-events disabled to allow toggle */ 
    background-color: #ee0; 
    outline: 0; 
} 
#top:focus + #bottom { 
    pointer-events: all; 
} 
#bottom { 
    position: absolute; 
    background: #f00; 
    pointer-events: none; 
    opacity: 0; 
    cursor: pointer; 
    height: 10rem; 
    width: 10rem; 
} 

HTML

<div tabindex="0" id="top"></div> 
<div id="bottom" tabindex="0"> 
</div> 
<!-- tabindex allows div to be focused --> 
Please click the square<br>above. Again. 
+1

這是一個很好的答案,但畢竟我決定堅持使用JavaScript。這是一個很好的實驗主題,深入研究CSS的侷限性,並從中學習一些東西。 – basement