如何将表格单元格中的文本替换为长度完全相同的文本

How would you replace text within a table cell with the text the exact same length?

本文关键字:文本 文本替换 表格 单元格      更新时间:2023-09-26

我需要在<table>单元格中替换日期和短语,而不使用固定宽度。

<table>
   <thead>
      <tr><th>Date</th></tr>
   </thead>
   <tbody>
      <tr><td id='changethis'>Wed Dec 21 2011</td></tr>
   </tbody>
</table>
var hold = $('#changethis').text();
setInterval(function () { 
  if ($('#changethis').hasClass("highlight")) { 
    $('#changethis').text(hold);
    $('#changethis').removeClass("highlight");
  }
  else {
    $('#changethis').text(" E  R  R  O  R ");
    $('#changethis').addClass("highlight");
  }
},1000);

问题是,每当文本交替出现时,表格都会重新格式化列的宽度。是否可以计算渲染文本的宽度并相应地调整交替文本??JSbin此处

您可以尝试将宽度添加到元素

$('#changethis').width($('#changethis').width());

http://jsbin.com/ozunan/3/edit

计算渲染文本宽度:

$.fn.textWidth = function(){
    var sensor = $('<div />').css({margin: 0, padding: 0});
    $(this).append(sensor);
    var width = sensor.width();
    sensor.remove();
    return width;
};

你可以完成剩下的