如何在jQuery的animate()
內設置position:relative
屬性,該元素沒有初始position
屬性集?jQuery在動畫函數中設置css位置
這不起作用:
$(mLinks[id]).animate
(
{
position:'relative',
left:'200px'
}
);
鑑於mLinks
是一個有效的DOM元素對象。
我也試過duration
和callback
參數。
如何在jQuery的animate()
內設置position:relative
屬性,該元素沒有初始position
屬性集?jQuery在動畫函數中設置css位置
這不起作用:
$(mLinks[id]).animate
(
{
position:'relative',
left:'200px'
}
);
鑑於mLinks
是一個有效的DOM元素對象。
我也試過duration
和callback
參數。
這是沒有意義的「動畫」的css position
屬性是不是?有relative
和absolute
或static
或類似的東西之間沒有什麼...
這是我會做什麼:
$(mLinks[id]).css('position', 'relative').animate
(
{
left:'200px'
}
);
如果你讀了相應的jQuery doc,你會發現這一點:
most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color() plugin is used).
animate
方法不讓你設置CSS屬性,這是有道理的,雖然有一個偉大的動畫,你必須正確設置CSS屬性,這是兩個不同的東西。
所以首先你應該設置CSS屬性。而且你應該使用css
方法:
$(mLinks[id]).css("position", "relative")
後,您可以用動畫的開始:
$(mLinks[id]).animate({ left:'200px' });
全部組合在一起,你將有:
$(mLinks[id]).css("position", "relative").animate({ left:'200px' });
看看這段代碼。
<html>
<head>
<title>Hello there</title>
<script type="text/javascript" src = "assets/js/jquery.min.js"></script>
</head>
<body>
<div class="tobechanged" style = "background:#ddd;position:fixed;">
hello there.
</div>
<script type="text/javascript">
$('.tobechanged').css('position','relative').animate({
opacity: 0.9,
left: '+=50'},
4000, function() {
//some stuff here.
});
</script>
</body>
</html>
這現在應該工作得很好。
哦,我明白了,是的。這很簡單。謝謝。 – Lee
'float:'呢?我知道這是非數值的,但如果你不知道某個元素的尺寸怎麼辦?或者你需要首先通過JS來確定它們嗎? – Lee
你也不能動畫'浮動'。我不確定你想要做什麼...逐漸改變佈局?就像,在http://jsfiddle.net/AfFtz/你想要文本神奇地走到div的權利?不幸的是,jquery不是那麼聰明..... – luiges90