最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Is it possible to subtract a number from inline style injected by JavaScript? - Stack Overflow

programmeradmin2浏览0评论

I have an inline style added to the HTML, like style="left: 10px;". Can I add/subtract to that number?

I would like to create a rule where I can remove 8px from that number no matter what that number is.

I tried using the ugly !important hack to override it, but that doesn't help when the initial value is changed.

I have an inline style added to the HTML, like style="left: 10px;". Can I add/subtract to that number?

I would like to create a rule where I can remove 8px from that number no matter what that number is.

I tried using the ugly !important hack to override it, but that doesn't help when the initial value is changed.

Share Improve this question edited Apr 24, 2013 at 11:58 user1726343 asked Nov 26, 2012 at 16:12 zadubzzadubz 1,3012 gold badges21 silver badges36 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 17

From 1.6 onwards, you can use the convenient:

$('#myelem').css('left','-=8px')

If for some strange reason you are stuck in the past, use:

$('#myelem').css('left', function(i,v) {
    return v - 8;
});

for jQuery 1.4 up.

Maybe you can use margin-left -8px instead. I don't know what you are looking for, but it might do the trick without JavaScript.

There is no CSS rule for such. However, you can do the same using JavaScript.

Assume you have,

.my_left {
   left: 10px;
}

And HTML elements like below,

<div class="my_left">My Div</div>
<div class="my_left">My Div</div>

Then using the below script, you can remove 8px from its current left value:

$(function () {
   $('.my_left').css('left', function (i, ov) {
       return ov - 8;
   });
});

You can use a variable for it, in order to be able to add or subtract:

var x=10;

x=x-parseInt(5);

x=x+parseInt(5);

<div id='something' style="left: "+x+"px"></div>

I've recently found on css-tricks that you can override inline css with

.myClassName[style] {
   left:5px!important;
}

http://css-tricks.com/override-inline-styles-with-css/

发布评论

评论列表(0)

  1. 暂无评论