背景覆盖整个网页的图像具有响应性,也是随机选择的

时间:2016-12-17 23:31:53

标签: javascript jquery html css

我正在尝试创建一个具有背景图像的页面,该图像使用css封面属性,以便它在浏览器中响应,但不会失真但是从jQuery中的数组中随机选择。

我没有太多代码,因为这是我目前唯一正在做的事情,我一直在玩,但我对jQuery没有太多处理,所以我真的不知道是什么我在做!任何帮助表示赞赏!

HTML:

<head>
    <title>Test</title>
    <link href="css/css.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="javascript/jquery.js"></script>
</head>
<body>
    <div id="background">   
    </div>  
</body>

CSS:

body {
    margin: 0;
}

#background {
    width: 100%;
    height: 100%;
    margin: 0;
    background-repeat: no-repeat;
    background-size: cover; 
    background-image: url(backgroundImage)
}

html, body { 
    overflow: none !important; 
    overflow-x: none !important; 
    overflow-y: none !important; 
}

jQuery的:

var picArr = ['Images/IMG_3764.jpg', 'Images/IMG_3793.jpg', 'Images/IMG_4050.jpg', 'Images/IMG_4323.jpg', 'Images/IMG_4351.jpg', ];

var myNumber = Math.floor(Math.random() * 5);

$(document).ready(function () {
    $("background-image").attr('url', picArr[myNumber]);
});

3 个答案:

答案 0 :(得分:1)

如果要将其随机化,请使用setTimeout()

此外,要更改&#34;背景&#34; div,只是.css jquery选择器,如下所示。

例如

var picArr = ['Images/IMG_3764.jpg', 'Images/IMG_3793.jpg', 'Images/IMG_4050.jpg', 'Images/IMG_4323.jpg', 'Images/IMG_4351.jpg', ];

$(document).ready(function () {
  setTimeout(function(){
    var myNumber = Math.floor(Math.random() * 5) + 1;

    $("#background").css('background-image', 'url('+picArr[myNumber]+')'); //here
  }, 3000); // ms of how often you want it to change.
});

答案 1 :(得分:0)

你没有错误地选择了$("background-image"),这不应该是$("#background")

var picArr = ['Images/IMG_3764.jpg', 'Images/IMG_3793.jpg', 'Images/IMG_4050.jpg', 'Images/IMG_4323.jpg', 'Images/IMG_4351.jpg', ];

var myNumber = Math.floor(Math.random() * 5);

$(document).ready(function () {
    $("#background").attr('url', picArr[myNumber]); //here
});
#background {
    width: 100%;
    height: 100%;
    margin: 0;
    background-repeat: no-repeat;
    background-size: cover; 
    background-image: url(backgroundImage)
}
<link href="css/css.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="javascript/jquery.js"></script>
<div id="background">
</div>

答案 2 :(得分:0)

我想这已经回答了,但这是我的解决方案:

`RDD that travels through time to compute things faster`

<强> CSS:

var picArr = ['http://lorempixel.com/output/fashion-q-c-640-480-1.jpg', 'http://lorempixel.com/output/animals-q-c-640-480-4.jpg', 'http://lorempixel.com/output/nightlife-q-c-640-480-2.jpg'];

var l = picArr.length;

var myNumber = Math.floor(Math.random() * l);

console.log(myNumber);

$(document).ready(function () {
    $("#background").attr('style', 'background: url(' + picArr[myNumber]) + ')';
});