简体   繁体   English

使用javascript将背景图像随机化

[英]using javascript to randomise a image in background

I am trying to randomise a image in a background, I am having problems because there is content already in the div 我正在尝试将背景中的图像随机化,因为存在div中的内容,所以出现了问题

this is what i got so far 这就是我到目前为止

        <div class="welcome-inner">
        <script type="text/javascript">
<!--
 var imlocation = "welcome/";
 var currentdate = 0;
 var image_number = 0;
 function ImageArray (n) {
   this.length = n;
   for (var i =1; i <= n; i++) {
     this[i] = ' '
   }
 }
 image = new ImageArray(3)
 image[0] = 'background1.jpg'
 image[1] = 'background2.jpg'
 image[2] = 'background3.jpg'
 var rand = 60/image.length
 function randomimage() {
    currentdate = new Date()
    image_number = currentdate.getSeconds()
    image_number = Math.floor(image_number/rand)
    return(image[image_number])
 }
 document.write("<img src='" + imlocation + randomimage()+ "'>");
//-->
</script>

CONTENT

</div>

the div welcome-inner already has styling in the css div welcome-inner内部样式已在CSS中

.row-welcome {
border-bottom: 0;
width: 100%;
margin: 0 auto;
overflow: auto;
margin-top: -20px;
background-position: 50% 50%;
background-size: cover;
border-bottom: 1px solid #1e346a;
}

welcome-inner did have a background image but I removed the line to try to get this to work welcome-inner确实有背景图片,但我删除了该行以尝试使其生效

The problem I am having is that the images are showing up but pushing my content down. 我遇到的问题是图像正在显示,但将我的内容压低了。

how do I adapt this to make it work? 我如何适应它才能使其正常工作?

You're going to need to set the background-image style (if you're using jQuery this will be easier). 您将需要设置背景图像样式(如果使用的是jQuery,这会更容易)。 So, instead of creating an tag which goes in the normal document flow, something more like this: 因此,与其创建普通文档流程中使用的标签,不如像这样:

$("#welcome-inner").style("background-image", imlocation + randomimage());

And change "#welcome-inner" to whatever the selector is for the DOM element you want to set the background-image on. 并将"#welcome-inner"更改为要设置背景图片的DOM元素的选择器。

I think your entire approach is incorrect. 我认为您的整个方法都不正确。 Try using .sort() , like: 尝试使用.sort() ,例如:

var doc = document;
function E(e){
  return doc.getElementById(e);
}
function range(least, greatest){
  var r = [];
  for(var i=0,n=least; n<=greatest; i++,n++){
    r[i] = n;
  }
  return r;
}
var rng = range(1, 3);
rng.sort(function(){
  return Math.round(Math.random())-0.5;
});
for(var i in rng){
  var img = new Image();
  img.src = 'welcome/background"+rng[i]+".jpg';
  //  If you add an id called pickAnId to your welcome-inner className div then
  E('pickAnId').appendChild(img);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM