文字淡出/阅读更多 链接

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 提供适合您旅程各个阶段的云产品。 立即开始使用 $200 免费信用额度!

读者 Rob Young 在 Newsweek.com 上看到了一个很酷的效果。

来自此处的截图

文字在底部淡出,并带有“更多...”链接。 文字淡出在这里并不新鲜。 我已经有了 演示 很久了,它使用透明 PNG 文件覆盖在文字之上。 但由于这是一个略有不同的想法,并且时代在变化,我们可以更进一步地发展这个想法。

假设这些小文本框用在侧边栏中,因此我们的 HTML 标记将是一个带有 sidebar-box 类别的 div。 此 div 可以包含任意数量的段落元素,其中最后一个将具有 read-more 类名,其中包含一个链接按钮。

<div class="sidebar-box">
  <p>malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
  <p class="read-more"><a href="#" class="button">Read More</a></p>
</div>

框的高度将通过适当的属性 max-height 限制,其 overflow 设置为隐藏。 我们还将使用相对定位,因为我们需要它在阅读更多段落上使用绝对定位,该段落锁定在框的底部,并使用 CSS3 渐变实现文字淡出。

.sidebar-box {
  max-height: 120px;
  position: relative;
  overflow: hidden;
}
.sidebar-box .read-more { 
  position: absolute; 
  bottom: 0; 
  left: 0;
  width: 100%; 
  text-align: center; 
  margin: 0; padding: 30px 0; 
	
  /* "transparent" only works here because == rgba(0,0,0,0) */
  background-image: linear-gradient(to bottom, transparent, black);
}

这给了我们

使用 jQuery 的“显示”

使此方法起作用的最简单方法是在点击时从侧边栏框中删除 max-height CSS。 这将使它立即扩展到所有包含段落的自然高度。 从理论上讲,您可以使用 CSS3 和 :target 来实现这一点,但这只是暂时的,会导致页面跳下。 我们可以使用 JavaScript 和 jQuery 的简单动画使它更优雅。

var $el, $ps, $up, totalHeight;

$(".sidebar-box .button").click(function() {
      
  totalHeight = 0

  $el = $(this);
  $p  = $el.parent();
  $up = $p.parent();
  $ps = $up.find("p:not('.read-more')");
  
  // measure how tall inside should be by adding together heights of all inside paragraphs (except read-more paragraph)
  $ps.each(function() {
    totalHeight += $(this).outerHeight();
  });
        
  $up
    .css({
      // Set height to prevent instant jumpdown when max height is removed
      "height": $up.height(),
      "max-height": 9999
    })
    .animate({
      "height": totalHeight
    });
  
  // fade out read-more
  $p.fadeOut();
  
  // prevent jump-down
  return false;
    
});

因此,用简单的话来说,当在一个 sidebar-box 内点击一个按钮时,找到所有相关的参与者(父元素等),测量一个新的理想高度,动画到那个新的高度,然后删除按钮。

查看演示   下载文件

关于透明度和渐变的快速说明

我花了一些时间试图弄清楚一个使用 CSS3 渐变并从“透明”淡化为常规十六进制颜色的 奇怪的问题 。 它似乎颜色正在乘到背景上。 实际上发生的是,单词“透明”实际上只是映射到“rgba(0, 0, 0, 0)” ,这意味着“完全透明的黑色”。 因此,当构建渐变时,中间颜色与不完全透明的黑色混合。 为了解决此问题,您需要在起始颜色和淡化为的颜色中使用 RGBa 颜色,即使它是完全透明的。 例如,对于红色从红色淡化为透明

background-image: -webkit-gradient(
  linear,
  left top,
  left bottom,
  color-stop(0, rgba(255, 0, 0, 0)),
  color-stop(1, rgba(255, 0, 0, 100)));

不要忘记所有其他渐变语法。 CSS3 Please! 是一个获取最新的 CSS3 语法的绝佳资源。

感谢 @foodgoesinmouth@sebnitu@maddesigns 和其他人...