简体   繁体   中英

jquery how to regex css style positive to negative, negative to positive?

jquery how to regex css style positive to negative, negative to positive?

var aaa='<p style="top:10px;left:-10px;">text</p>';
aaa.attr('style').replace(/\-/gi,'').replace(/\d+/gi,'-$&');//this will replace negative to positive, then positive to negative, so nothing change

But I need some effect like:

top:10px;left:-10px; => top:-10px;left:10px;

However, the style could be other rules. another example effection:

top:-100px;left:200px; => top:100px;left:-200px;

As Rooster commented, use a function that multiply matched number with -1. The return value of the function is used as replacement string.

var aaa='<p style="top:10px;left:-10px;">text</p>';
aaa.replace(/[-\d]+/g, function(x) { return -parseInt(x); })
// => "<p style="top:-10px;left:10px;">text</p>"

Using jQuery you can do it like this :

$(aaa).css('left', function (i, value) {
    return -parseInt(value);
});

Here is a demo (click the red box) : http://jsfiddle.net/wared/s6M43/ .

I know your question was 'jquery how to regex css style positive to negative, negative to positive?' don't know what you want to achieve but maybe here is a css solution?

$('.content').click(function () {
$(this).toggleClass("left");
});

http://jsfiddle.net/aronez/s6M43/4/

Greets

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM