Don't overwrite css properties, but add to them with jQuery

后端 未结 3 534
情歌与酒
情歌与酒 2021-01-23 00:29

I just want to know how to use the jquery .css() function to not overwrite, but to add additional values to css properties.

For instance, I have an element that is curre

相关标签:
3条回答
  • 2021-01-23 00:47

    Save the current style, then concatenate:

    var rotation = 0;
    function rotate() {
        rotation += 90;
        var rotationString = 'rotate(' + rotation + 'deg)';
        var current = $('#square').css('transform');
        $('#square').css('transform', current +' '+ rotationString);
    }
    

    http://jsfiddle.net/oqqubda8/

    It works, and I don't know if there's another way to do it.

    0 讨论(0)
  • 2021-01-23 00:51

    The reason that it overrides the value instead of adding to it is simply due to how the cascade works. Namely, you're setting a value on the transform property, which like all other CSS properties can only have one value at a time, therefore as far as the API is concerned you're overwriting its existing value with a new one. In CSS, this is what it might look like:

    #square {
        transform: translate(-50%, -50%);
        transform: rotate(90deg);
    }
    

    As you can see, this will result in the second declaration overriding the first.

    CSS does not support partial or additive property declarations, and likewise there is no way to directly add a value to an existing property without causing the existing value to be lost.

    Essentially, this means you will have to include the existing transform in the new value when you set it. Since you are setting it using jQuery, you can retrieve the existing value using the .css() getter, then concatenate your new transform and apply the result, saving you the need to hardcode the existing value:

    var currentTransform = $('#square').css('transform');
    var rotationString = 'rotate(' + rotation + 'deg)';
    var newTransform = currentTransform + ' ' + rotationString;
    $('#square').css('transform', newTransform);
    

    The main problem with this is that triggering this particular block of code again will cause currentTransform to contain the rotation as well. This will continue adding rotations each time. If this is not desired, you will either need to write some checks, or failing that, unfortunately, hardcode the value.

    0 讨论(0)
  • 2021-01-23 01:01

    Since transform is kind of a shorthand, the values must be combined... There's no increment method.

    What you could do, is retrieve the previous value and append the new one:

    Updated JsFiddle

    var rotation = 0;
    function rotate() {
        rotation += 90;
        var rotationString = 'rotate(' + rotation + 'deg)';
        var prev = $('#square').css('transform');
        $('#square').css('transform', prev + " " + rotationString);
    }
    
    0 讨论(0)
提交回复
热议问题