动态更改图像高度

时间:2012-10-18 18:27:24

标签: php html css image

您好我正在尝试动态生成不同的多个图像高度。这很像pinterest布局。我需要一个特定的最小高度,如100px左右。然后我需要一个像400px这样的最大高度。然后我需要为不同的图像改变这个高度。

这是我的代码:

<div class="pin_image">
    <a href="<?php the_permalink(); ?>">
        <img width="191" height="auto" class="<?php echo $img_class; ?>" src="<?php echo PricerrTheme_get_first_post_image(get_the_ID(),102,72); ?>" />
    </a>
</div>

这是我主页上所有图片的代码。

2 个答案:

答案 0 :(得分:1)

使用PHP的rand()。在那里设置最小 - 最大值。

<img height="<?php echo rand(100, 400); ?>" class="<?php echo $img_class; ?>"

最高价值为400;最低的将是100。

与此相关的一个怪癖是它可以/将以一位数递增;但是,我认为这是一个起点。你可能会更聪明地将它全部包装在一个函数中,这样你的过程代码就会容易一些。

function pinIt() {
 $n = rand(100,400);
 // cool code here to ensure the value is divisible by 20 //
 // just a thought
 return $n;
}

<img height="<?php echo pinIt(); ?>"  class="<?php echo $img_class; ?>" />

编辑: 像这样...

<?php
    function pinIt() {
        $n = rand(100, 400);
        if($n % 20 != 0) {
            $n += 20 - ($n % 20);
        }
        return $n;
    }
?>

<img height="<?php echo pinIt(); ?>"  class="<?php echo $img_class; ?>" />

答案 1 :(得分:0)

我不知道我是否得到了你真正想做的事情,但是如何为你的img元素添加一个css类。 E.g:

.myclass { min-height: 100px; max-height: 400px; }

修改

回答你的第二个问题。实际上不确定你想要做什么,但让我们尝试至少有一个想法。

您可以使用Javascript生成随机数,并将其应用于类height的元素的属性.myclass。 jQuery会有所帮助:

var height = Math.floor((Math.random()*300)+100);
$('.myClass').attr('height', height);