расширение div для выявления переполнения при нажатии

0

Я рассматриваю этот пример на этом веб-сайте. Я хотел создать эффект, подобный этому, где у вас есть <div>, в котором есть несколько <p>, и есть кнопка, чтобы показать полное расширенное описание. Я проанализировал html, и он выглядит так:

<div class="product-description">
   <div class="desc-wrap" itemprop="description">
      <p>Material: wool
         <br>6 Colors: Black, Yellow, Gray, Wine Red, Green, Navy Blue
         <br>Size: One size only
         <br>Recommended for size SMALL
         <br>It has been noted by customers that these skirts are short.
         <br>*Please check the measurement picture for sizing information. There are no refunds on orders that were messed up on your behalf.
      </p>
      <p>Note: Due to the difference between different monitors, the color may be off a tiny bit.</p>
      <p>WORLDWIDE SHIPPING!
      </p>
   </div>
   <div class="desc-fade"></div>
   <div class="open-link" style="display: block;"><a href="javascript:;">Expand Full Description</a></div>
</div>

Я предполагаю, что есть функция javascript, которая расширяет поле при нажатии. Но что это? Как воспроизвести этот эффект?

5 ответов

1
Лучший ответ

Вот пример того, что вы хотели: http://jsfiddle.net/kedem/D9NCP/

CSS:

    .product-description {
        height:150px;
        overflow: hidden;
        position:relative;
    }
    .product-description.open {
        height:auto;
        overflow: hidden;
        position:relative;
    }
    .desc-fade {
        width: 200%;
        margin-left: -50%;
        height: 30px;
        background: #fff;
        z-index: 1;
        position: absolute;
        -webkit-box-shadow: 0 0 20px 30px #fff;
        -moz-box-shadow: 0 0 20px 30px #fff;
        box-shadow: 0 0 20px 30px #fff;
        bottom: 0;
        left: 0;
        opacity: 1;
        -webkit-transition: opacity 250ms, 1s;
        -moz-transition: opacity 250ms, 1s;
        -o-transition: opacity 250ms, 1s;
        transition: opacity 250ms, 1s;
    }
    .open-link {
        position:absolute;
        bottom: 15px;
        z-index:2;
    }

JQuery:

     $(function () {
        var wrapHeight = $(".product-description .desc-wrap").height();
        var descHeight = $(".product-description").height();

        if (wrapHeight <= descHeight) {
            $(".product-description .desc-fade").hide();
            $(".product-description .open-link").hide();
        }

        $(".product-description .open-link").click(function () {
            $(this).hide();
            $(".product-description .desc-fade").hide();
            $(".product-description").animate({
                height: wrapHeight
            }, 1000);
        });
    });
  • 0
    Здравствуйте. Как бы вы сделали это для двух div рядом друг с другом на одной странице?
0

Вот полный код

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
    var $divView = $('div.view');
    var innerHeight = $divView.removeClass('view').height();
    $divView.addClass('view');

    $('div.slide').click(function() {
        $('div.view').animate({
          height: (($divView.height() == 110)? innerHeight  : "110px")
        }, 500);
        return false;
    });
});

</script>
<style>
.view{
    overflow:hidden;
    height: 110px;

}
.total{
border:1px solid;
/*height:130px;
overflow-y:auto;*/
}
</style>
</head>
<body>
<div class="total">
<div class="view">
  <p>shown/hidden depending on the toggle above. </p>
  <p>shown/hidden depending on the toggle above. </p>
  <p>shown/hidden depending on the toggle above. </p>
  <p>shown/hidden depending on the toggle above. </p>
  <p>shown/hidden depending on the toggle above. </p>
  <p>shown/hidden depending on the toggle above. </p>
  <p>shown/hidden depending on the toggle above. </p>
  <p>shown/hidden depending on the toggle above. </p>
  <p>shown/hidden depending on the toggle above. </p>
</div>
<div class="slide" style="cursor: pointer;">Show/Hide</div>
</div>
</body>
</html>
0

Как насчет этого:

http://jsfiddle.net/VvBRh/

Что я наделал:

$('.open-link a').click(function(){

     if($(".desc-wrap").css("height") == "60px") {

        //Find auto height of div and save it

        $('.desc-wrap').css('height', 'auto');
        var autoHeight = $('.desc-wrap').height();

        //Revert back to 2 lines

        $('.desc-wrap').css('height', '60px');

        //Animate to the saved autoHeight

        $(".desc-wrap").animate({height: autoHeight}, 1000);

    } else {

        //Shrink back to 2 lines (you can remove this if you want)

      $(".desc-wrap").animate({height: "60px"}, 1000);

    }
    return false;
});

Вам также нужно добавить немного css для получения настроек:

.desc-wrap { height: 60px; overflow: hidden }

Я уверен, что это может быть более элегантным, и вы можете получить высоту из двух строк вместо фиксированных px, но я оставлю это вам решать;)

  • 0
    Здравствуйте. Как бы вы сделали это для двух div рядом друг с другом на одной странице?
0

Используя DOM-инспектор, это поможет вам понять трюк. Сначала они используют постоянную высоту для контейнера. Onclick удаляет текст и расширяет div, устанавливая большую высоту.

Однако мы должны определить общую высоту div, поэтому мы не должны скрывать расширенную часть с самого начала

http://jsfiddle.net/2SMF2/2/

$('.expand').click(function () {
     $('#test').removeClass('collapsed', 'fast')
     $(this).remove();
});
0

Это работает для вас? Демо-версия JSFIDDLE

HTML

<div class="div-wrapper">
    <div class="hider">
        <p>Here goes your text that is partially shown Here goes your text that is partially shown Here goes your text that is partially shown Here goes your text that is partially shown Here goes your text that is partially shown Here goes your text that is partially shown Here goes your text that is partially shown Here goes your text that is partially shown Here goes your text that is partially shown Here goes your text that is partially shown Here goes your text that is partially shown Here goes your text that is partially shown </p>
    </div>
    <a href="javascript:void(0);" class="open-link">Show all</a>
</div>

CSS

/* this first one is not necesary */
.div-wrapper {
    width:300px;
    border:solid 1px #000;
}

.div-wrapper>.hider {
    height: 100px;
    transition: ease-in-out all 0.2s;
    overflow:hidden;
}

Jquery

$(document).ready(function(e) {
    $('.open-link').click(function(e) {
       var $wrapper = $(this).parent().find('.hider');
       $wrapper.css('height',$wrapper.find('p').height());
       $(this).remove();
    })
});

дайте мне знать, если это полезно.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню