【问题标题】:jQuery cut text without slicing wordsjQuery剪切文本而不切片单词
【发布时间】:2020-06-16 07:24:15
【问题描述】:

我知道,这个问题已经被问过好几次了,很抱歉重复了一遍,但我似乎无法在这些答案中找到我的问题的解决方案。

我有一个选择的文本,我想在这么多单词之后剪切,然后单击,将其余的单词重新添加回来 - 就像手风琴风格一样。

我已将文本切成两半,然后使用 jQuery 将它们重新组合在一起,但它会将单词切成两半。我想在这句话之后切断它。我不确定我这样做的方式是否是最好的方法,所以如果有人有任何其他想法,或者他们是否知道如何在单词之后切断,而不是在中间,将不胜感激。

$(".about__profiles--team .text").text(function() {
  var introText = $(this).text().substring(0, 150);
  var panelText = $(this).text().substring(150);

  $(this).html('<span class="accordion-button">' + introText + '</span><span class="panel">' + panelText + '</span>');
});

$('.accordion-button').click(function() {
  $(this).parent('#accordion').toggleClass('open-accordion');
});
.text {
  border-bottom: 1px solid black;
  padding-bottom: 30px;
  margin-bottom: 0;
  position: relative;
}

.accordion-button {
  transition: ease 0.4s;
  cursor: pointer;
  outline-style: none;
  -webkit-touch-callout: none;
  -webkit-tap-highlight-color: rgba(0,0,0,0);
}

.accordion-button:before {
  content: '+';
  display: block;
  color: black;
  height: 10px;
  width: 10px;
  position: absolute;
  bottom: 10px;
  right: 0;
  transform: rotate(90deg);
  transition: ease 0.4s;
}

.panel {
    display: none;
    transition: ease 0.4s;
}

.open-accordion > .accordion-button:before {
  transform: rotate(-90deg) !important;
}

.open-accordion > .panel {
  display: inline !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="about__profiles--team">
  <h3 class="job-title">Title</h3>
  <h2 class="name">LOREM IPSUM</h2>
  <div class="text" id="accordion">Lorem ipsum dolor sit amet, consectetur adipiscing. Mauris tri accumsan, pulvinar purus a, facilisis ligula. Fusce mi a velit ul, consectetur adipiscing Mauris tristique eu orci ac sodales. Vestibulum id accumsan, pulvinar purus a, facilisis ligula. Fusce mi a velit ultrices, id porta arcu viverra. Nunc pia enim, id egestas dolor bibendum nec.</div>
</div>

谢谢

【问题讨论】:

  • 相信你在找slideToggle()函数
  • 很难准确捕捉,因为每个单词都会有所不同。除了 Yotam dahan 的想法,还可以定义 css 的三个点。案例分析:stackoverflow.com/a/486571/6115840一往下滑,就把css三点类去掉,往上滑动就可以再添加

标签: jquery


【解决方案1】:

不要在单词中间切开搜索下一个空格。所以作为最简单的方法替换

var introText = $(this).text().substring(0, 150);
var panelText = $(this).text().substring(150)

var index = $(this).text().indexOf(' ', 150);
var introText = $(this).text();
var panelText = '';
if(index !== -1)
{
    var introText = $(this).text().substring(0, index);
    var panelText = $(this).text().substring(index+1);
}

请注意,这是非常基本的。你也可以用“.”、“”、“-”等分割。我不确定150是否是正确的选择

【讨论】:

  • 感谢克劳斯的建议。我添加了该代码,但出现错误 - “未捕获的 SyntaxError:意外数字” - 无法完全弄清楚这里出了什么问题。有什么想法吗?
  • 很抱歉,括号太多了。我编辑了它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-15
  • 1970-01-01
  • 1970-01-01
  • 2011-07-24
  • 2023-04-09
  • 1970-01-01
  • 2021-12-07
相关资源
最近更新 更多