【问题标题】:Randomly Set Width of Image with Jquery使用 Jquery 随机设置图像的宽度
【发布时间】:2014-09-07 13:03:56
【问题描述】:

我希望将图像的宽度设置为 25% 到 75% 之间的随机数,这可以通过 Jquery 实现吗?到目前为止,我已经尝试了我能想到和研究的一切,但无济于事..

有人可以帮忙吗?

我对 JQuery 不太了解,因此非常感谢您的帮助

我正在尝试使用插件 Instafeed 从带有特定主题标签的用户帐户中随机化图像大小,因此我完全拥有:

我需要 .insta-box 在每次加载图像时随机生成一个大小...

<style>
.insta-box {float:center;clear:both;margin:0px;padding:0%;max-height:50%;overflow:hidden;border-width:0;display:inline-block;}</style>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
    <script>
    (function ($) {
        var userId = "UID";
        var accessToken = "Token";
        var numDisplay = "9";
        $.ajax({
            type: "GET",
            dataType: "jsonp",
            cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?    access_token="+accessToken,
            success: function(data) {
                for (var i = 0; i < numDisplay; i++) {                      
        var rand = Math.floor(Math.random()*10)+10+"%";
            $(".insta-box").css('width', rand);
$(".insta").append("<div class='insta-box'><a target='_blank' href='"+data.data[i].link+"'>
    <img class='instagram-image' src='" + data.data[i].images.low_resolution.url+"'width='auto'/><a></div>"); 
            $(".insta").css('width', '100%');
            }    

            }
        });
    })(jQuery);
    </script>

【问题讨论】:

  • 简答;是的你可以。给我们看一些代码......你尝试了什么,你在哪里卡住了?
  • @PeterVR 更新了初始帖子

标签: jquery css random width


【解决方案1】:

给你,窗口宽度的 25% 到 75% 之间的宽度:DEMO

var rand=Math.floor(Math.random()*75)+25;
var width=Math.round(($(window).width()/100)*rand);
$('img').width(width);

更新:

只需将这一行 $(".insta-box").css('width', rand); 替换为以下内容

 $(".insta-box").eq(i).css('width', rand);

【讨论】:

  • 当我将图像更改为与我的图像在由 instafeed 插件放入时具有相同的 id 但加载图像时随机化大小时,我可以看到它在你的小提琴上工作,例如这里www.bchsalevelmaths.co.uk/test 底部的画廊是我试图用这个随机化来影响的地方
  • @TaylorMudd 在您的示例中,每个图像的 id 为“instafeedimage”。如果您想定位多个元素,请使用类,而不是 id。
  • @scdavis41 啊是的.. 代表我犯了愚蠢的错误,但这并没有改变任何东西..
  • @AminJafari 这很可能是我的实现,但您能否看看我的初始邮政编码并指导我在哪里粘贴什么?抱歉,我已经被这个项目深深卷入了..
  • 我认为 img hight:auto; 的 css 可能有问题,删除它并告诉我是否可以解决问题
【解决方案2】:

这会将图像的宽度设置为 25-75 之间的随机百分比:

width = Math.floor((Math.random() * 50) + 25).toString();
$("#instafeedimage").width(width + '%');

工作演示here

【讨论】:

  • 这与上面 Amin Jafari 的回答有同样的问题,我可以看到它在你的小提琴上工作,但它只是不想在我的文档中工作,不确定这是否是由于 instafeed 插件.. .
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 1970-01-01
  • 2010-12-11
  • 1970-01-01
  • 2015-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多