設置一個具有指定高度的外部div的想法對我來說不是一個可行的解決方案。我的php代碼是一個模板,我的div的內容總是在變化 - 根據用戶點擊的鏈接從數據庫中提取內容。這個div位於頁面頂部,其他信息必須正確顯示在其下。
所以,我想出了這個解決方案對我來說效果很好。
首先,我從CSS中刪除了設置高度並添加了「display:none;」 - 這允許div加載完全打開,但用戶看不到它。
然後我使用JavaScript(本例中爲jQuery)來獲取高度。接下來,在jQuery中,我將顯示設置爲block,並將高度設置爲我需要的「關閉」設置。最後,我用動畫中的獲得的高度來滑動div'open'。
的CSS代碼:
#main_description {
position: relative;
display: none;
/*height: 8.92855em; -> this was the original 'closed' height*/
border-bottom: 1px solid #a9a5a6;
overflow: hidden;
}
中的JavaScript:
var state = true;
var descriptionHeight = $("#main_description").height();
// for testing -> alert("Description Height: " + descriptionHeight);
$("#main_description").css({"display" : "block", "height" : "8.92855em"});
$("#main_description_toggle").click(function()
{
if (state)
{
$("#main_description").animate({
height: descriptionHeight + "px"
}, 1000);
$("#main_description_toggle").html("<a>less ▲</a>");
}
else
{
$("#main_description").animate({
height: "8.92855em"
}, 1000);
$("#main_description_toggle").html("<a>more ▼</a>");
}
state = !state;
});
(我知道,8的高度。92855em似乎很奇怪,但是這是行高的5倍,客戶想要5行文本來顯示div何時「關閉」)。
「高度」屬性在'%'用法上很少按照預期工作。你確定你不能用'bottom:0'或'top:0'來做這個動畫嗎? – 2012-07-16 12:58:12
你能提供更多信息嗎?你的HTML看起來像什麼?你喜歡哪種風格?也許提供一個http://jsfiddle.net會有所幫助。另外高度:100%;在大多數情況下不會像人們希望的那樣工作。 – Christoph 2012-07-16 12:58:16
爲html和正文標記添加100%高度,然後再試一次 – 2012-07-16 12:58:55