dousi1097 2013-08-25 01:42
浏览 52
已采纳

使用javascript动态计算表标题宽度 - 如何? (PHP - > javascript变量赋值)

I'm currently attempting to write a dynamic table where the heading width is split in equal widths equally across the required number of columns (PHP variable "$numberofcolumns").

Firstly, could someone please give me a hand popping some more code in that would make it easy for me to calculate the table heading widths dynamically? So far I have only got as far as turning the php variable into a JavaScript variable $noofcolumns -> var columnno as shown below - I'm now completely lost!

My total table width remaining to use is 80% (20% already used for a fixed width column).

i.e.
if columnno = 3 -> table heading width = 80% / 3
if columnno = 4 -> table heading width = 80% / 4
etc...

I have tried using the calc() CSS3 function previously, but this doesn't display correctly in a fair amount of browsers! (hence the requirement for javaScript!) Due to this issue, it would be easier if the outcome of the JavaScript code gave a value in pixels!

<script type="text/javascript">
var columnno = <?php echo $numberofcolumns; ?>;
</script>

Secondly, am I correct in thinking that I can retrieve the calculated JavaScript variable (as javaScript is client side...) by using a PHP function such as: $_REQUEST['javascript_variable_name_here']?

  • 写回答

1条回答 默认 最新

  • dongyan1625 2013-08-25 09:17
    关注
    <script type="text/javascript">
    var columnno = <?php echo $numberofcolumns; ?>;
    var headingWidth = Math.floor(80 / columnno);
    var lastHeadingWidth = 80 - headingWidth;
    
    // now you assign these values to your columns. I'd suggest you use jQuery, assign a class to each column (col1, col2, etc., using PHP), and then:
    
    // we assume i = 1 is that 20% fixed column
    for(i = 2; i < columnno; i++) {
        $('.col' + i).css('width', headingWidth + '%');
    }
    $('.col' + columnno).css('width', lastHeadingWidth + '%');
    </script>
    

    Why Math.floor and lastHeadingWidth? If you divide 80 by 3 and then multiply the result by 3 you'll find out you are missing 0.0000000000001 pixels (it's all about internal number representation and precision). Also, some browsers automatically round float values to 3-4 decimal places, so accounting for this difference yourself is more consistent. Yes, for odd column numbers the last one will be slightly larger.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制