Problems copying some css styles from element to element
Hi, I'm trying copy some css styles from an img style attribute to a another span element style. This code allows me to copy the background-color, but not any of the other styles from the img element. Here is an example with the padding style.
As you can see, it returns nothing as the value, whereas changing the padding for background-color in jquery does return a value (sames goes for border -- ie. nothing).
Unfortunately I cannot access your web page because my antivirus is warning me of potential malware problem is your web site.
If the CSS in the img tag is not an inline "style" attribute then you will certainly not be able to access the padding or border.
You will certainly need to go through the 4 values: padding-top, padding-right, padding-bottom and padding-left.
And the same goes from the border or margin.
If however the the img tag actually have an inline style="..." attribute, you can just copy the value of that attribute and set it verbatim to the style attribute of your span tag.
Please copy and paste both the HTML of the img and the span tag in your reply if you need further assistance. I will then be able to determine what the issue is.
$('img[alt]').each(function() {
var img = $(this);
// create the wrap div
var theWrap = $('<div class="imgWrapper"></div>');
// add the wrap div to the DOM
$(img).after(theWrap);
var captionText = img.attr('alt');
var style = $(this).css("padding");
// put the content into the wrap div
$(theWrap).append(img);
$(theWrap).append('<br /><span class="imgCaption" style="padding:' + style + '">' + captionText + '</span>');
// I was trying different things here...
//$(".imgCaption").css("background-color", $("img").css("background-color") );
//$(".imgCaption").css("border", $("img").css("border") );
You need to understand that border, padding and margin are just CSS shorthand and do not translate in JavaScript and jQuery. If you want for instance to copy the padding from he image to the caption you would write:
$(".imgCaption").css({'padding-top':$('img').css('paddingTop'), 'padding-right':$('img').css('paddingRight'), ...});
You will therefore need to add each a padding property for each side.
The same goes for the margins and the borders.
You could go faster if you just want to transfer the style attribute of the img to he element with imgcaption class by:
$('.imgCaption').attr('style', $('img').attr('style'));
That will just copy the "style" attribute from the img element to the element with that class name
Bookmarks