2012-09-05 58 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

我希望这有助于!