获取当鼠标悬停在使用JavaScript的表格上时选择的列数和行数

时间:2015-12-31 03:56:28

标签: javascript jquery html-table

基于创建下图像的HTML表格....

enter image description here

我需要允许用户将鼠标移动到表格单元格上,当它们向右/向上/向下移动时,它会将CSS类添加到覆盖空间SizeChooser-hover中的每个单元格。

当他们为那个表选择所需的列和行并单击它时,会将CSS类SizeChooser-selected添加到正方形中的所有单元格。

然后它还会在JavaScript中为我提供列数和行数。

任何人都可以帮助我实现这一目标吗?我的JSFiddle在这里有表https://jsfiddle.net/qxavaja9/

的HTML

添加一个CSS类`cell-selected

2 个答案:

答案 0 :(得分:1)

编辑:这仅适用于悬停

$('table td').on('mouseover', function(){
    //remove the current selected
    $('table td').removeClass('SizeChooser-hover');
    //get the indices (position)
    var x = $(this).index();
    var y = $(this).parent().index();
    //iterate over each row
    $('table tr').each(function(){
        //if the row is less than or equal to the selected row
        if($(this).index() <= y){
            //iterate over each cell in the row
            $(this).children('td').each(function(){
                //if the cell is less than or equal; add the class
                $(this).toggleClass('SizeChooser-hover', $(this).index() <= x);
            });
        };
    });
});

点击后,只需将所有SizeChooser-hover切换到Sizechooser-selected

$('table td.SizeChooser-hover').on('click', function(){
    $('.SizeChooser-hover').toggleClass('SizeChooser-hover Sizechooser-selected');
});

答案 1 :(得分:1)

var columns;
var rows;
$(function() {
  $('td').hover(function() {
    var n = $(this).index();
    var m = $(this).parent('tr').index();
    $('td').removeClass('SizeChooser-hover');
    $('tr').each(function(y) {
      $(this).find('td').each(function(x) {
        if (x <= n && y <= m) {
          $(this).addClass('SizeChooser-hover');
        }
      })
    })
  }).click(function(){
    columns = $(this).index();
    rows = $(this).parent('tr').index();
    $('td').removeClass('SizeChooser-selected');
    $('td.SizeChooser-hover').addClass('SizeChooser-selected');
  });
});

https://jsfiddle.net/qxavaja9/15/

columnsrows就是你想要的。

相关问题