2013-07-29 34 views
2

im嘗試在使用jQuery選擇器之前動畫定位固定。我們如何調用和動畫 :在jQuery選擇器之前,我通過調用類等知道其他方法。但我只想用jQuery來完成它。如何動畫定位固定:在選擇器之前用jQuery

HTML

<div id="main"></div> 

CSS

#main { 
    width:200px; 
    height:300px; 
    background:#000; 
} 
#main:before { 
    content:'im before'; 
    position:fixed; 
    left:0px; 
    top:0px; 
    width:40px; 
    height:40px; 
    background:blue 
} 

JS

$("#main").hover(function() { 
    $(this).animate({ 
     "margin-left": "40px" 
    }); 
    $("#main:before").animate({ 
     "margin-left": "40px" 
    }); 
}, function() { 
    $(this).animate({ 
     "margin-left": "0px" 
    }); 
    $("#main:before").animate({ 
     "margin-left": "0px" 
    }); 
}); 

http://jsfiddle.net/pr6Cg/3/

注:認罪e給我一些沒有任何插件的解決方案

+0

** jquery救援** ............... *不* – iConnor

回答

1

與你一樣使用JavaScript無法訪問僞元素,因爲它們是由CSS動態生成的,並且不存在於DOM中。 (如建議的Adrift

試試這個

#main:before { 
    content:'im before'; 
    position:relative;//use this 
    left:-10px; 
    top:-10px; 
    width:40px; 
    height:40px; 
    background:blue 
} 
+0

我已經在我的問題中提到,即時通訊嘗試動畫定位固定元素 – Hushme

+0

無法完成沒有CSS,因爲它不是DOM的一部分。 –

0

這是一個解決方案,但它不是跨瀏覽器,主要是Internet Explorer的版本,它使用CSS轉換,並且不需要jQuery的。

#main { 
    width:200px; 
    height:300px; 
    background:#000; 
    -webkit-transition: margin-left ease 0.3s; 
    transition: margin-left ease 0.3s; 
} 

#main:before { 
    content:'im before'; 
    position:fixed; 
    left:0px; 
    top:0px; 
    width:40px; 
    height:40px; 
    background:blue; 
    -webkit-transition: margin-left ease 0.3s; 
    transition: margin-left ease 0.3s; 
} 

#main:hover { 
    margin-left: 40px; 
} 

#main:hover:before { 
    margin-left: 40px; 
} 

的jsfiddle:http://jsfiddle.net/pr6Cg/4/

+0

我知道,但請閱讀我的問題,我想用jQuery做到這一點 – Hushme

+0

嗯,我不認爲它可以做到那麼,如果你擔心與CSS轉換回調,你仍然可以實現它與jQuery http:/ /stackoverflow.com/questions/9255279/callback-when-css3-transition-finishes – jerrylow

2

這是不可能的JavaScript,因爲你不能選擇不存在的元素。

你必須使用CSS像這樣,只需撥動一類

CSS:

div::before { 
    content:''; 
    position: fixed; 
    left:0; 
    right:0; 
    height:100px; 
    background:skyblue; 
    transition: all 500ms ease-in-out; 
    top:0; 
} 
div.active::before { 
    top: calc(100% - 100px); 
} 

的jQuery:

$('button').click(function(){ 
    $('div').addClass('active'); 
}); 

Demo

如果你不能這樣做,那麼我認爲你可能不得不想出一個不同的想法。

+0

當我懸停在:之前選擇其父母的動畫爲什麼? – Hushme

相關問題