【问题标题】:Generating a random location for text span inside a parent div为父 div 内的文本跨度生成随机位置
【发布时间】:2021-08-05 10:40:30
【问题描述】:

我正在开展一个项目,我正在根据从 API 获得的数据生成词云。我正在尝试找到一种方法来动态定位每个单词,同时避免碰撞并防止它们溢出到父 div 之外。为此,我需要以下信息: 呈现的文本的大小 所有单词的总空间(高度和宽度) 保存已呈现单词的索引。

我能够通过将每个单词定位在一个跨度内并将高度和宽度设置为自动而没有边距或填充来实现这一点。然后我可以使用injectedSpan.clientWidth 获取元素的宽度,使用injectedSpan.clientHeight 获取高度值。我还发现我可以使用injectedSpan.getBoundingClientRect() 并获取包含以下信息的对象:

x : 0

y : 50

width : 708

height : 0

top : 50

right : 708

bottom : 50

left : 0

获得这些信息后,我认为将文本渲染到唯一位置会很容易,但由于某种原因,仍有很多文本相互重叠。我编写了一个 JS 函数,它检查顶部和右侧的值是否在现有元素的范围内,如果是则生成一个新的唯一位置。我不确定我是否遗漏了一些明显的东西。到目前为止,这是我的代码:https://jsfiddle.net/amotor/3fuje46q/22/

【问题讨论】:

    标签: javascript css dom


    【解决方案1】:

    根据您的要求。

    function randomLoc(elm, parent){
      function randomNumber(min, max) {  
          return Math.floor(Math.random() * (max - min) + min); 
      }  
      let scH = parent.offsetHeight;
      let scW = parent.offsetWidth;
      
      elm.setAttribute("style", 'left: '+randomNumber(0, scW)+'px; top:'+randomNumber(0, scH)+'px;');
    }
    randomLoc(
    document.getElementById('testElm'),
    document.getElementById('parent')
    );
    #parent{
      width:400px;
      height:200px;
      background:yellow;
    }
    #testElm{
      position:relative;
    }
    <div id="parent">
      <button id="testElm">test</button
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      相关资源
      最近更新 更多