2016-09-19 98 views
1

我想爲文本的下劃線設置動畫。這是沒有問題的CSS。不過,我想用另一個文本來觸發第一個文本的動畫。我已經知道你不能在jQuery中使用:因爲它不是DOM的一部分。我見過這兩個線程:Access the css ":after" selector with jQuerySelecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery更改類:在用jquery選擇動畫之前爲動畫劃下劃線

但我找不到任何可行的解決方案。下面是代碼:https://jsfiddle.net/rbsxufsc/4/

HTML:

<h2 class='uno'> 
    <a href=''>:hover, please</a> 
</h2> 
<h2 class='dos'> 
    <a href=''>Animate above text</a> 
</h2> 

CSS:

h2 > a:before { 
    content: ""; 
    position: absolute; 
    width: 100%; 
    height: 3px; 
    bottom: 0; 
    left: 0; 
    background: #9CF5A6; 
    visibility: hidden; 
    border-radius: 5px; 
    transform: scaleX(0); 
    transition: .25s linear; 
} 
h2.uno > a:hover:before, 
h2.uno > a:focus:before { 
    visibility: visible; 
    transform: scaleX(1); 
} 

將鼠標懸停在第一個文本,它是很好的動畫。當懸停第二個文本時,我想再次爲第一個文本設置動畫,就好像第一個文本是懸停一樣。有沒有辦法做到這一點?

回答

1

您可以在dos元素上向uno元素onmouseover添加一個類。

,我添加的CSS是:

h2.uno.active > a:before { 
    visibility: visible; 
    transform: scaleX(1); 
} 

這裏是工作示例:

$(function() { 
 
\t $('.dos a').on('mouseover', function() { 
 
    \t $('.uno').addClass('active') 
 
    }).on('mouseout', function() { 
 
    \t $('.uno').removeClass('active') 
 
    }) 
 
})
@import url(http://fonts.googleapis.com/css?family=Quando); 
 
*, *:after, *:before { 
 
    box-sizing: border-box; 
 
    -moz-box-sizing: border-box; 
 
} 
 
* {margin:0;padding:0;border:0 none;position: relative; outline: none; 
 
} 
 
html, body { 
 
    background: #004050; 
 
    font-family: Quando; 
 
    font-weight: 300; 
 
    width: 100%; 
 
} 
 
h2 { 
 
    background: #0D757D; 
 
    width: 100%; 
 
    min-height: 200px; 
 
    line-height: 200px; 
 
    font-size: 3rem; 
 
    font-weight: normal; 
 
    text-align: center; 
 
    color: rgba(0,0,0,.4); 
 
    margin: 3rem auto 0; 
 
} 
 
.dos {background: #ff5e33;} 
 

 
h2 > a, h3 > a { 
 
    text-decoration: none; 
 
    color: rgba(0,0,0,.4); 
 
    z-index: 1; 
 
} 
 

 
h2 > a:before { 
 
    content: ""; 
 
    position: absolute; 
 
    width: 100%; 
 
    height: 3px; 
 
    bottom: 0; 
 
    left: 0; 
 
    background: #9CF5A6; 
 
    visibility: hidden; 
 
    border-radius: 5px; 
 
    transform: scaleX(0); 
 
    transition: .25s linear; 
 
} 
 
h2.uno > a:hover:before, 
 
h2.uno > a:focus:before, 
 
h2.uno.active > a:before { 
 
    visibility: visible; 
 
    transform: scaleX(1); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h2 class='uno'> 
 
    <a href=''>:hover, please</a> 
 
</h2> 
 

 
<h2 class='dos'> 
 
    <a href=''>Animate above text</a> 
 
</h2>

+0

輝煌!沒有想到這種方法。與此同時,我在沒有使用的情況下開發了一個解決方案。對於那些感興趣的人,這裏是代碼:https://jsfiddle.net/rbsxufsc/8/但我會採取您的解決方案,因爲它更多的是我搜索的解決方案。謝謝! – Sheldon

+0

你不止歡迎:) – Dekel