简体   繁体   中英

CSS attribute in jQuery not applying in DOM

OK so I have a jQuery interactive which is fed from a Google spreadsheet. I've created certain classes which are added if there are multiple divs in exactly the same position (.offset1, .offset2 etc.).

Ive added some css declerations which then shift those divs with those classes 20 or 40 pixels to the left or right...

$('.position4.offset1').css({'left':'+=20px;'});
$('.position4.offset2').css({'left':'+=40px;'});    
$('.position4.offset3').css({'left':'+=60px;'});    

No matter where I put these in my jQuery they don't seem to be applying to the actual page. I thought the extra specificity of these decelerations would get rid of any problems of it not adding.

You can see the currently confusing graphic here. Scroll down and you may see some of the dots are brighter. This is where there are overlaying divs. They have the appropriate classes but haven't shifted.

http://thetally.efinancialnews.com/tallyassets/pension-hole/index.html

Hope that makes sense. Thanks

If you want to achieve relative positioning like that, you can achieve it like so:

$('.position4.offset1').css({
     left: $('.position4.offset1').position().left + 20 + 'px'
});

Having answered this, I've realised that on later versions of jQuery what you've coded should work:

 $('div').css({ 'left':'+=20px;', 'top':'+=50px;' }); 
 div { background:red; height:30px; position:absolute; width:30px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div></div> 

Looking at your web page you have version 1.6.1 of jQuery. I would suggest either updating that to a more up to date version, or if that's more effort than it's worth, just use the first method I mentioned which does work. I've tested it using the console.

Update your jQuery version. Documentation specifies your properties should work in 1.6 forward but I could only achieve it in 1.7.2.

As of jQuery 1.6, .css() accepts relative values similar to .animate(). Relative values are a string starting with += or -= to increment or decrement the current value. For example, if an element's padding-left was 10px, .css( "padding-left", "+=15" ) would result in a total padding-left of 25px.

Also, if you want to update just one property, you can also do:

$('.position4.offset3').css('left', '+=60px');

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