Set div height in steps to fit tiled background
I need to control a div's height to always appear in steps of 20. I have a repeating div background that is 20 pixels high and I want the div to always end in a correct way. I found what I think is the solution here: Set height of an element on multiples of a number?
But when I try it doesn't work. I'm a newbie at jquery and probably made a simple mistake.
In the following test html code I'm expecting the div's height to always appear in steps of 100px, but it doesn't work.
<!DOCTYPE html PUBLIC "-//W3C开发者_如何学编程//DTD XHTML 1.0 Transitional//EN" "http://`enter code here`www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test jquery</title>
<script type="text/javascript" src="jquery.js"></script>
<script language=”javascript”>
$(document).ready(function(){
$('#testCol').height(function(i, h) { return Math.ceil(h / 100) * 100; });
});
</script>
<style type="text/css">
#testCol {
width: 150px;
background-color:#FFCC00;
}
</style>
</head>
<body>
<div id="testCol">df ds d sfdhs fdsf ds fhsdu ds iuhsdi fsdf dhsf sdiuh isdf iusd fiushd fiuds i uhsdiu isudf iusd fiusdh fiusd fih wtwpr wer rew</div>
</body>
</html>
Remove the language=”javascript” from the script tag. That's prevening the browser running the script. You don't need this directive but if you want to use it, it should be:
<script type="text/javascript">
To set the div's height in steps of 20px, I changed the values to the following:
<script type="text/javascript">
$(document).ready(function(){
$('#testCol').height(function(i, h) { return Math.ceil(h / 20) * 20; });
});
</script>
Some neat maths for this is as follows, just set the roundTo
variable to the number you wish to round to.
var height = parseInt($jQueryObj.height(), 10),
roundTo = 20;
if (height && (height % roundTo !== 0))
{
height = roundTo * Math.round(height / roundTo);
}
I have setup a demo fiddleof this in action here: http://jsfiddle.net/i_like_robots/uBcHh/
You may face issues with padding too so remember to add or subtract as necessary. You should probably set minHeight
rather than height
for safety. I would genuinely ask yourself or whoever asked for this feature if it is really necessary.
精彩评论