Simply JQuery math syntax- how do I subtract?
Hello wonderful community,
I am trying to do some really simple math with JQuery, but I can't find a cheatsheat with math syntax on it (that is relevant to what I'm trying to do). I know how to do additions & multiplication but subt开发者_运维百科raction is eluding me!
What I need to do is assign a style to "#photo" that has a value of (total width of viewport - (241px + (height*0.32))). This code is successfully grabbing the total width of the viewport and assigning it as the width of #photo:
$(document).ready(function(){
var width = $(window).width();
$('#photo').css('width', width);
});
But nothing I've tried by way of ('width', (width- (value + value))) has worked - can someone let me know what the syntax is for subtraction and nested equations?
OR, rather than calculate (height*0.32) again, how would I assign the output of (height*0.32) to a var so I can re-use it, making the width calculation something like ('width', (width- (281px - varname)))?
Here's the whole function including the (height*0.32) calc:
$(document).ready(function(){
var height = $(window).height();
var width = $(window).width();
$('#menu').css('height', height);
$('#menu').css('width', (height*0.29));
$('#menu').css('position','fixed');
$('#menu').removeClass('nojavascript');
$('#novel').css('padding-left', (height*0.32));
$('#novel').removeClass('nojavascript');
$('#photo').css('width', width);
});
Er, further tips on how to tidy my code also appreciated. Just looking at it I can guess at some things that might well be unnecessary duplications!
Edited per request: Here is the subtraction problem, which I've got working now:
$('img').css('width', (width - (281+(height*0.32))) + 'px');
Now the problem I'm wrestling with is how to calculate a height for img so that it preserves a 4:3 photo ratio! But it's nearly 4am so that will have to wait til morning.
For formatting, a few things. jQuery can take objects for CSS, so pass everything in, in a single go. Secondly, only when the key isn't a valid javascript identifier (see "padding-left") do you need quotes around it. Third, jQuery objects chain, so you can follow the css()
call with the removeclass()
call in-line. And finally, indenting is really, really your friend.
And finally, the height
and width
functions return bare integers, but the css()
function requires that you include units. The most fundamental unit, and the one returned by height
and width
, is pixels:
$(document).ready(function() {
var height = $(window).height(), width = $(window).width();
$('#menu').css({height: height + 'px', width: (height * 0.29) + 'px', position: 'fixed'})
.removeClass('nojavascript');
$('#novel').css({'padding-left': (height * 0.32) + 'px'})
.removeClass('nojavascript');
$('#photo').css({width: width + 'px'});
});
精彩评论