如何在页面加载时使用一组ID数组为身份标记生成随机ID [英] How to generate a random ID for body tag upon page load using a set array of IDs
问题描述
这是我的问题:
现在我有一个非常简单的html网站传情,带有大背景图片(www.iambold.org)。
b$ b
背景图像设置在body标签上,背景颜色也是如此。我需要的是每当页面被加载时,身体标记被随机分配一个不同的ID。
原因是每个单独的ID将具有不同的背景图像和与之相关的不同背景颜色。
最后一部分是我需要生成器才能在我在css文件中设置的ID之间进行选择。
这里是CSS的身体背景:
body {font-family:'Lato',verdana,arial,无衬线字体;字体大小:14px的;行高:的22px; }
body#body_1 {background:#fff url(../ images / bg_splash.jpg)center -15px repeat-x;}
body#body_2 {background:#353932 url(../ images / bg_splash2.jpg)center -15px repeat-x;}
我熟悉jquery,可以破解代码的能力足以做我所需要的,但我不够好为自己的代码编写这些类型的代码。 解决方案
ol> 示例没有jQuery需要这个简单的脚本): Here's my issue: I have a very simple html website teaser right now with a large background image (www.iambold.org). The background image is set up on the body tag, and so is the background color. What I need is for the body tag to be randomly assigned a different ID whenever the page is loaded. The reason for this is that each separate ID will have a different background image and different background color associated with it. The last part is that I need the generator to only select between the IDs that I have set in the css file. Here's the CSS for the body backgrounds: I am familiar with jquery, and can hack codes well enough to do what I need, but I am not good enough to write my own code for these types of things. Example (no jQuery needed for this simple script): The 这篇关于如何在页面加载时使用一组ID数组为身份标记生成随机ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
Math.random()$>生成一个随机整数c $ c>和
Math.floor()
。
id
属性设置为该元素的值。
$(function(){//< - 这是jQuery,因为` document.body`不存在
//在文档头部
var styleIds = [body1,body2];
document.body.id = styleIds [Math.floor(Math.random()* styleIds.length)];
});
Math.random()
方法返回满足 0 <= x <0的随机数。 1
。 Math.floor
编号。列表大小为2时,可能的数字是:0和1,这是我们想要的,因为数组的索引是从零开始的。body {font-family:'Lato',verdana,arial,sans-serif; font-size:14px; line-height:22px; }
body#body_1 {background:#fff url(../images/bg_splash.jpg) center -15px repeat-x;}
body#body_2 {background:#353932 url(../images/bg_splash2.jpg) center -15px repeat-x;}
Math.random()
and Math.floor()
.id
attribute to the element's value.$(function(){ //<-- That's jQuery, because `document.body` does not exist
// in the head of the document.
var styleIds = ["body1", "body2"];
document.body.id = styleIds[ Math.floor(Math.random()*styleIds.length) ];
});
Math.random()
method returns a random number satisfying 0 <= x < 1
. Math.floor
floors the number. With a list size of 2, the possible numbers are: 0 and 1, which is what we want, because indexes of arrays are zero-based.