jquery issue (bug?) in IE with .css() manipulation
I have a block of jquery / javascript code that sets the left margin of an image depending on the browser width.
I do some sums to calculate the required left margin and it goes in var $diff.
This code works fine:
$('#background-wrapper>img').attr('alt',$diff);
which demonstrates that the sums are all working fine as the ima开发者_StackOverflow中文版ge ends up with the correct value for $diff inserted in its alt attribute. This works on IE, FF, Chrome.
But if I change the code to:
$('#background-wrapper>img').css('margin-left',$diff);
then firefox and chrome work fine, using $diff as a value for the images left-margin as I intended, but IE throws a run time error and stops running the script, citing an Invalid Argument in jquery file. I'm using jquery 1.3.2.min.
Any ideas?
Heres the code for the full function.
function imageResizeCenter() {
var $windowh = jQuery(window).height();
var $windoww = jQuery(window).width();
var imagesrc = $('#background-wrapper2>img').attr('src');
var myimage = new Image();
myimage.src = imagesrc;
var $width = myimage.width;
var $height = myimage.height;
var $ratio = parseInt($width,10)/parseInt($height,10);
var $newwidth = parseInt($windowh,10)*$ratio;
var $diff = (parseInt($windoww,10)-parseInt($newwidth,10))/2;
if($diff<0) $diff=0;
$('#background-wrapper2>img').attr('height',$windowh).css('margin-left',$diff);
}
Maybe
$('#background-wrapper>img').css('margin-left',$diff + 'px');
Using Javascript to set CSS properties has a little caveat: Instead of using dashes to separate multi-word properties, you use camelCasing. So margin-left
should be marginLeft
...
$('#background-wrapper > img').css('marginLeft', $diff);
精彩评论