Clone style in jQuery?

后端 未结 9 1584
轻奢々
轻奢々 2021-02-05 03:56

I have a called spn1, which has some style from inline + CSS file.

I have another called spn2

相关标签:
9条回答
  • 2021-02-05 04:16

    UPDATE

    Check this fiddle: http://jsfiddle.net/9BJ5y/


    Better idea would be clone spn1 and replace spn2 with it.

    i.e. something like:

    var x = $('#spn2').html();
    $('#spn2').replaceWith($('#spn1').clone().html(x).attr('id', 'spn2'));
    
    0 讨论(0)
  • 2021-02-05 04:21

    Is there a reason you're not simply doing .clone(true)?

    http://jsfiddle.net/johncmolyneux/6Fz84/

    This example copies inline and class styles, but not id styles (which could be very useful).

    0 讨论(0)
  • 2021-02-05 04:21

    Why not applying whatever rules to both elements at the time?

    Something like:

    $('spn1','spn2').css({color: 'red'});
    

    You could use multiple selectors http://api.jquery.com/multiple-selector/

    0 讨论(0)
  • 2021-02-05 04:26

    Try this:

    $("#spn2").attr("style", $("#spn1").attr("style"))
        .addClass($("#spn1").attr("class"));
    
    0 讨论(0)
  • 2021-02-05 04:26

    <div style='background-color:red; display:hidden' id='template'>
        <span>Something</span>
    </div>
    

    var replica=$('#template').clone();
    replica
    .removeAttr('id')
    .css('display', 'block')
    .find('span').text('Whatever');
    replica.appendTo('#container');
    
    0 讨论(0)
  • 2021-02-05 04:29

    Take a look at this thread: https://stackoverflow.com/a/6416527/541827
    The idea is to copy all the style's properties from one item to another

    Or just use the jquery.copycss.js plugin, the answer is based on.
    Usage:

    $('#some-element').copyCSS('#another-element');  // copy all styles
    $('#some-element').copyCSS('#another-element', ['top', 'left']);  // copy just top and left
    $('#some-element').copyCSS('#another-element', null, ['top', 'left']);  // copy everything except top and left
    
    0 讨论(0)
提交回复
热议问题