2012-09-05 57 views
1

工作原型: http://jsfiddle.net/ad5qa/K5fdZ/28/jQuery的擴大DIV父innerHTML的高度

因爲當更多的按鈕被點擊的parentsUntil被抓在頁面的所有div某種原因。我只是想獲得div.htmlbox並有高度自動,所以我可以看到完整的內容。然後點擊減少將其縮小回50px高度。任何幫助將不勝感激。

$('.morebox a').toggle(function() { 
    var $this = $(this); 
    var $parent =$this.parentsUntil('.htmlbox'); 

    $parent.height('auto') 
    $this.text('less') 
    $parent.css('border', '2px solid magenta') 
    $this.css('border', '2px solid red') 
}, function() { 
    $parent.height('50px') 
    $this.text('more') 
});​ 

<h3>Description</h3> 
<div class="htmlbox"> 
This is a samle description that goes here with short or long content in this panel. If the text is higher than 50px then it should be hidden by the box. You must click expand to view the remaining content in the html box div. The float box is used to cut off the overflow of the content. 
<div class="fade-overlay"></div> 
</div> 
<div class="morebox"> 
    <img align="absmiddle" alt="more-less grabber" src="http://goo.gl/ho277"> 
    <a href="#" style="line-height: 10px">more</a> 
    <img align="absmiddle" alt="more-less grabber" src="http://goo.gl/ho277"> 
</div> 
+1

請總是直接包含在你的問題相關的代碼。如果jsfiddle不復存在,這個問題應該仍然對其他人有用。 –

+1

根據你的HTML,似乎'.htmlbox'是'.morebox'的父親。例如,'.htmlbox'是'fade-overlay'的父級,但與'.morebox'的級別相同。 – Chase

回答

1

如果你只想要一個元素,那麼你就不會使用parentsUntil,你會使用closest然而.htmlbox是不是你a的祖先都沒有。你需要做更復雜的事情。此外,您需要使用this而不是全選a s。

$this.closest(".morebox").prev(); 

請注意,這是高度依賴於您當前的HTML。如果您更改結構,則需要修改此結構。

+0

非常好 - 我以前玩過但不是最接近的。謝謝 – user1649305

0

含每個段落+更多的按鈕,在一個div然後使用下面的代碼來選擇更多按鈕:

http://jsfiddle.net/K5fdZ/44/

<div class="section">  
    <div class="htmlbox"> 
     MY_TEXT 
     <div class="fade-overlay"></div> 
    </div> 
    <div class="morebox"> 
     <img align="absmiddle" alt="more-less grabber" src="http://goo.gl/ho277"> 
     <a href="#" style="line-height: 10px">more</a> 
     <img align="absmiddle" alt="more-less grabber" src="http://goo.gl/ho277"> 
    </div> 
</div> 

var $parent = $('.morebox a').parent().find('.htmlbox'); 
+0

您的代碼暗示'.htmlbox'位於'.morebox'內。事實並非如此。您也正在選擇每個「.morebox a」,而不僅僅是一個正在採取行動的人。 –

+0

看我的編輯。也看看更新的jsfiddle。 – Lowkase

+0

用這個html,你會想'$ this.closest(「。section」)。find(「。htmlbox」)' –

0

考慮包裝各.htmlbox.morebox一個div內,使用jQuery $。最接近()和$ .find()遍歷DOM,如下所示:

HTML

<div class="boxcontent"> 
    <h3>Description</h3> 
    <div class="htmlbox"> 
     ... 
    </div> 
    <div class="morebox"> 
     ... 
     <a href="#" style="line-height: 10px">more</a> 
     ... 
    </div>    
</div> 

JS

$('.morebox a').toggle(function() { 
    var $el = $(this); 
    var $parent = $el.closest('.boxcontent').find('.htmlbox'); 

    $parent.height('50px') 
    $el.text('more') 
}, function() { 
    var $el = $(this); 
    var $parent = $el.closest('.boxcontent').find('.htmlbox'); 

    $parent.height('auto'); 
    $el.text('less') 
}).trigger('click');​ 

Updated JSFiddle here

我希望這有助於!