Html and Internet Explorer: How to avoid hidden el

2019-02-27 15:07发布

问题:

I've a TABLE, in a HTML5 document.

I've a view selector who hide/show some rows, using jQuery hide() and show().

When user select the table (programmatically, using a 'select all' button, see below for the code), and then copy/paste into, for example, Word or Outlook email, the behaviour is different from FF and IE.

  • FF: doesn't copy elements with style='display: none;'. It's desired and expected behaviour
  • IE: copy ALL, and paste ALL, so my visual 'trick' is then useless for IE users.

I add my selectAll function. Simply expect a selector and select all the text inside it. It's something I copy/pasted from the jQuery forum.

jQuery.fn.selectText = function(){
    var doc = document;
    var element = this[0];
    // console.log(this, element);
    if (typeof element == 'undefined') {
        return;
    }
    if (doc.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    } else if (window.getSelection) {
        var selection = window.getSelection();        
        var range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    }
};

How can I select only visible elements ? Or... is there any other html/js trick?

BTW I'll downvote whoever will propose to:

  • change users

  • force users to change browser

  • ask me to render only visible cells and change server code

回答1:

It seems like this question has been asked before multiple times. (1) - (2)

It seems like there has not been a response that works fine for everyone.

You could use is.(':visible') in jQuery but not sure that translates back to javascript (not very good at it).

Other people have suggested cloning the table and only copying what's in the other table which is hidden, but then that causes a problem later on with other browsers which work fine.

You could use the above method which would work but it's a nasty hack.

There is an answer here which may be of interest to you, however I'm not sure what you're trying to copy and if this is worth the effort.

<joke>

If all else fails, here are some other recommendations:

  • change users

  • force users to change browser

  • render only visible cells and change server code

</joke>



回答2:

Nasty hack, but you could:

  • clone the table with js onload somewhere else on the page with a display:none
  • 'Hiding' rows actually removes them from the DOM of the original table
  • restoring hidden rows by replacing from hidden cloned version of table