【问题标题】:JQuery: return div to initial heightJQuery:将div返回到初始高度
【发布时间】:2016-01-28 17:46:03
【问题描述】:

我试图让一些 div 对我的 mouseOver 和 mouseOut 做出反应。我正在尝试构建类似于 Vimeo 风格的音量栏的东西。

我正在让条形图对 mouseOver 做出反应,但我希望它们在 mouseOut 之后返回到原来的高度。每个条的高度不同。当它被硬编码时它可以工作,但我试图使用尽可能少的代码。

这是我的 JQuery:

$(document).ready(function() {
var totalHeight = '100%';
var initHeight;

function getHeight(h) {
  initHeight = h;
  //alert(initHeight);
}

$("div#barWrap").children().mouseover(function() {
    // This is where I am having trouble. I want to get the original height of the bar so I can reuse it on mouseOut
    getHeight($("div#barWrap").children().css('height')); 
    // Animate bar
    $(this).animate({ height: totalHeight}, 100);
});

$("div#barWrap").children().mouseout(function() {
    $(this).animate({ height: initHeight}, 400);
});

});

任何帮助将不胜感激。

【问题讨论】:

    标签: jquery height


    【解决方案1】:

    将初始高度存储为每个元素的数据:

    var totalHeight = '100%',
        $bwc = $('div#barWrap').children();
    
    $bwc.each(function(i,el) {
        $(this).data('height', $(this).height());
    });
    
    $bwc.mouseover(function() {
        $(this).animate({ height: totalHeight}, 100);
    });
    
    $bwc.mouseout(function() {
        $(this).animate({ height: $(this).data('height') }, 400);
    });
    

    【讨论】:

    • 这解决了问题!非常感谢!
    【解决方案2】:

    我会使用 data() 函数来存储 div 的属性:http://api.jquery.com/jQuery.data/

    【讨论】:

      【解决方案3】:

      如果您能够针对现代浏览器,另一种解决方案是使用 CSS 过渡。

      【讨论】:

        【解决方案4】:

        将一个带有height:auto 的div 放入另一个带有overflow:hiddenheight:0 的div,然后点击后检查inner div 的高度,并将其设置为outer。试试看!

        HTML:

        <div id="visible-by-year" class="filter-visible">
            <div id="content"><br><br><br><br><br><br><br><br><br></div>
        </div>
        

        CSS:

        .filter-visible{
        background: gray;
        height: 0;
        #content{
            height: auto;
            position: relative;
        }
        

        }

        JS

          $('.by-year').on('click', function() {
             //$('.visible-by-year').toggleClass('show-by-year')
             //
            // $('#visible-by-year').animate({ height: $("#visible-by-year").data('height') }, 400);
             var contentHeight = $('#content').height();
             $('#visible-by-year').animate({ height: contentHeight}, 500 );
        
             console.log(contentHeight);
        
        
         });
        

        【讨论】:

          猜你喜欢
          • 2015-06-19
          • 2015-05-07
          • 2011-04-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-31
          • 2014-01-19
          • 2021-02-13
          相关资源
          最近更新 更多