如何将我的代码更改为jQuery而不是纯JS?

时间:2017-06-17 19:14:39

标签: javascript jquery

我正在尝试在jQuery上设置一个函数而不是纯JS,我收到一个错误:

 15 | prev.css('height') = prev.scrollHeight + "px";
                                               ^ Expected an assignment or function call and instead saw an expression.

这是实际代码:

function expand(target)
{
  let prev = target.previousElementSibling;
  
  prev.style.height = prev.scrollHeight + "px";
  target.style.display = "none";
}
#p {
  height: 50px;
  overflow: hidden;
}

#read-more {
  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: 200px;
}
<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' onclick="expand(this)">
    READ MORE
  </div>
</div>

我试图在这里设置:

var toggleReadMore = function() {
    $('#read-more').click(function(e) {
        var prev = $(this).prev();            
        prev.css('height') = prev.scrollHeight + "px";
        $(this).hide();            
    });
};

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您无法像这样分配值,您需要将其更改为

prev.css('height', prev.scrollHeight)

第二个参数接受滚动高度。如果有多个CSS属性,您可以传递像

这样的对象
prev.css({
  height: 'some height here',
  width: 'some width here'
});

答案 1 :(得分:1)

**改变第3行如下**

var toggleReadMore = function() {
$('#read-more').click(function(e) {
    var prev = $(this).prev();            
    prev.css('height', 50);
    $(this).hide();            
  });
};