不要覆盖CSS属性,而是使用jQuery添加到CSS属性中 [英] Don't overwrite css properties, but add to them with jQuery

查看:213
本文介绍了不要覆盖CSS属性,而是使用jQuery添加到CSS属性中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想知道如何使用jquery .css()函数不覆盖,而是向CSS属性添加其他值.

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

例如,我有一个元素,当前在其上具有css transform:translate(-50%, -50%).而且我想使用jQuery .css()函数添加transform: rotate(90deg),但是当我使用它时,它会覆盖它.

For instance, I have an element that is currently has the css transform:translate(-50%, -50%) on it. And I want to use the jQuery .css() function to ADD transform: rotate(90deg), but when I use it, it overwrites it.

如果我的描述令人困惑,请查看这个小提琴. http://jsfiddle.net/justinbchristensen/mvhwbjLo/1/

Check out this fiddle if my description is confusing. http://jsfiddle.net/justinbchristensen/mvhwbjLo/1/

您将在小提琴中看到,当您第一次单击按钮时,正方形将失去其原始的变换,向下滑动并旋转,但是随后在按钮上进行的所有单击均会旋转正方形,因为它不会丢失'transform:translate '属性.

You will see in the Fiddle that when you first click the button, the square loses its original transformation, slides down, and rotates, but all subsequent clicks on the button simply rotate the square because it's not losing the 'transform:translate' property.

我不想在我的.css()函数element.css('transform', 'translate(-50%,-50%) rotate(90deg)'中说,我只想能够将旋转添加到现有转换中.

I don't want to have to say in my .css() function element.css('transform', 'translate(-50%,-50%) rotate(90deg)', I just want to be able to add the rotate to the existing transformation.

有什么办法吗?

推荐答案

由于transform是一种简写形式,因此必须将值进行组合...没有增量方法.

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:

更新的JsFiddle

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

这篇关于不要覆盖CSS属性,而是使用jQuery添加到CSS属性中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆