如何在文本上设置线性渐变?

时间:2017-06-17 21:12:21

标签: javascript jquery html css

所以这就是我想要实现的目标:

(忽略绿松石细胞)

enter image description here

正如您所看到的,由于应该在文本上方的渐变,整个文本都很模糊。单击READ MORE按钮时,元素应该一直到底部并删除渐变,当您单击READ LESS时,它应该恢复到原始状态。

现在设计看起来不像我在代码中所做的那样,我完全需要它。但是我的想法已经不多了,以便得到与设计中完全相同的东西。

有什么建议吗?

这是代码:

$(document).ready(function(){
    var toggleReadMore = function() {
      $('#read-more').click(function(e) {
          $(this).prev().animate({'height': $(this).prev()[0].scrollHeight + 'px'}, 400);
          $(this).hide();
          $(this).next('#read-less').show();
      });
      $('#read-less').click(function(e) {
          $(this).prev().prev().animate({height: '90px'}, 400);
          $(this).hide();
          $(this).prev('#read-more').show();
      });

    };
    toggleReadMore();
}());
#p {
  height: 50px;
  overflow: hidden;
}
#read-less {
 display: none;
}
#read-more,
#read-less {
  background: linear-gradient(to bottom, rgba(255,0,0,0), rgba(255,255,255,1));
  color: blue;
  cursor: pointer;
  position: absolute;
  bottom: -20px;
  padding: 15px 0;
  text-align: center;
  width: 100%;
}

#wrapper {
  position: relative;
  width: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='wrapper'>
  <p id='p'>Pinterest taxidermy et heirloom, ennui enim eu bicycle rights fugiat nesciunt commodo. High Life food truck jean shorts in. Blog asymmetrical cold-pressed photo booth. Neutra chia in, mustache Etsy nostrud plaid kogi. Magna polaroid stumptown aliqua put a bird on it gentrify, street art craft beer bicycle rights skateboard. DIY plaid gentrify, sustainable sapiente seitan mumblecore viral cardigan. Nisi pariatur laborum cornhole kitsch tempor fingerstache Bushwick. </p>
  <div id='read-more'>
    READ MORE
  </div>
   <div id='read-less'>
    READ LESS
  </div> 
</div>

2 个答案:

答案 0 :(得分:1)

您可以使用:after after,background gradient和z-index实现此目的。

.masked{
  background: white;
  z-index: 1;
  position:relative;
}

.masked:after {
  content: "";
  position: absolute;
  top:0;
  left:0;
  width:100%;
  height: 100%;
  z-index: 2;
  background: -webkit-linear-gradient(rgba(255,255,255,0) 0%, rgba(255,255,255,1) 70%);
  background: -moz-linear-gradient(rgba(255,255,255,0) 0%, rgba(255,255,255,1) 70%);
  background: -o-linear-gradient(rgba(255,255,255,0) 0%, rgba(255,255,255,1) 70%);
  background: linear-gradient(rgba(255,255,255,0) 0%, rgba(255,255,255,1) 70%);
}

这里的代码段完全符合您的需求:https://jsfiddle.net/9bp1rc0e/1/

答案 1 :(得分:1)

这是一个你要找的例子吗? http://jsbin.com/guwititube/edit?html,css,js,output

如果是,那么您可以通过使用附加到“Read more”按钮的jquery onClick函数更改article:after的高度来使其可读。如果有大量文本,可能会改变article元素本身的高度。

此示例来自此帖子How to apply a CSS gradient over a text, from a transparent to an opaque colour