【问题标题】:how to fill a screen width/height in razor page with string如何用字符串填充剃刀页面中的屏幕宽度/高度
【发布时间】:2018-09-14 20:53:37
【问题描述】:

我正在寻找一种在剃须刀页面内用动态字符串填充 div 或段落宽度的方法。例如,假设我有一个句子“我非常喜欢饼干”,我有一个 div,它有一个宽度和一个高度,我把“我喜欢饼干”放在开头,“much”放在最后,然后在中间我想用 "very"s 填充 div 而不换行或溢出。

<div class="col-md-6">
I love cookies 
<script>js_magic()</script>
much!
</div>

想要的输出:

我非常非常非常非常非常非常非常喜欢饼干!

好像“非常”这个词只要有足够的宽度就应该重复。

在 C# 中,我知道怎么做,我使用图形和字体、字符串长度等...但是 js 和 jQuery 对我来说总是一团糟。

【问题讨论】:

  • 你的例子不是很清楚。但如果您要使用完全相同的句子,您可以使用$(div selector).text() 获取字符串内容,然后根据位置使用substring() 对其进行操作。如果您不打算始终使用该句子(这更现实),则需要使用占位符或模式来替换,例如“我非常喜欢 cookie {emphasis}”并将 {emphasis} 替换为您需要的任何内容。
  • 等一下,我去编辑

标签: javascript jquery html razor-pages


【解决方案1】:

在这种情况下,您需要通过添加至少一个然后测量它的宽度并计算可以插入多少来填充宽度来知道非常的绘图尺寸。 Working JSBin

还可以将此样式添加到您的容器 white-space: nowrap; 以防止不必要的包装

更新:添加评论

//this function takes 2 strings and inserts str2 into str at a specific position and returns the result
function insertString(str,ind,str2){
  return str.slice(0, ind) + str2 + str.slice(ind);
}

function fillInVery(){
  // capture the text content from HTML container
  var s = $("#container").text();
  // the text to be inserted multiple times (wrapped in order to be selected)
  var very = "<span class='very'>very </span>";

  console.log(s);
  // insert one VERY string to the text
  s = insertString(s,15,very);
  // replace the old string with the new one to be rendered
  $("#container").html(s);

  console.log(s);
  // get the width of the inserted and rendered VERY word
  var veryw = $('.very:first').width();
  var contw = $('#container').width();
  var contpw = $('#container').parent().width();
  // calculate the difference (space) between the container and its parent and divide it over the width of one VERY to get how many can fit in the remaining space
  var countInsert = Math.floor((contpw - contw)/veryw);

  // add VERY word to fill the space
  for(var i =0 ; i< countInsert; i++){
    s = insertString(s,15,very);
  }
  // replace the text and render it
  $("#container").html(s);
}

fillInVery();

【讨论】:

  • 非常有趣,谢谢。能否请您添加 cmets 以便我更好地理解它?
  • @GuyDresher cmets 添加
  • 请注意,这不是性能优化的代码,您仍然可以最小化 split 函数的使用,这比仅连接字符串然后插入它更重。你明白了..
  • 其实没有:)你能解释一下吗?
  • 而不是这个for(var i =0 ; i&lt; countInsert; i++){ s = insertString(s,15,very); } 你应该这样做var verys=""; for(var i=0;i&lt;countInsert;i++) verys+=very; s= insertString(s,15,verys);
猜你喜欢
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 2020-05-24
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 2022-12-14
相关资源
最近更新 更多