简体   繁体   English

页面上的随机图像作为超大背景加载

[英]Random image on page load as Jumbotron background

I am trying to get the following code to load a random image for a jumbotron background without success. 我正在尝试获取以下代码来为超大背景加载随机图像而没有成功。 I just can't tell which part is the problem. 我只是不知道问题出在哪一部分。 The jumbotron itself is acting as the area for a basic flex slider. 巨无霸本身就是基本的flex滑块的区域。 I basically want the background image for the flex slider to change on every page load. 我基本上希望flex滑块的背景图像在每次加载页面时都发生变化。

To attempt this, I've placed the following script in the head section of the page: 为此,我将以下脚本放置在页面的顶部:

<script type="text/javascript">
$(document).ready(function() {
    var images = ['01.jpg', '02.jpg'];
    $('.jumbotron').css({'background-image': 'url(../images/jumbotron/' + images[Math.floor(Math.random() * images.length)] + ')'});
});

and my Jumbotron CSS looks like: 我的Jumbotron CSS看起来像:

.jumbotron {
position: relative;
color: #fff;
/*text-align: center;
text-shadow: 0 1px 3px rgba(0, 0, 0, .4), 0 0 30px rgba(0, 0, 0, .075);*/
/*background:url(../images/header-bg.jpg) no-repeat #232a31; /* Old browsers */
height:630px;
background-size:cover;
overflow:hidden;
}

I have disabled the 'background:url' line (which otherwise loaded one image), to allow the enforcement of the 'background-image:url' in the script. 我已禁用“ background:url”行(否则将加载一幅图像),以允许在脚本中强制执行“ background-image:url”。 Well, no image loads at all! 好吧,根本没有图像加载! http://webeutic.com/123.html http://webeutic.com/123.html

Can anyone lend an extra hand scratching my head? 任何人都可以伸出额外的手挠我的头吗? Thanks to all 谢谢大家

You have an Uncaught TypeError: undefined is not a function in 123.html @ line: 215. 您遇到了Uncaught TypeError:123.html @第215行中的undefined不是函数。

$(document).ready(function() {

It seems that the $() alias for jQuery() is not defined. 似乎未定义jQuery()的$()别名。 Use jQuery() instead. 使用jQuery()代替。

EDIT: With the first error fixed you will notice that your code tries to load images from the wrong location. 编辑:修复了第一个错误,您将注意到您的代码尝试从错误的位置加载图像。 That's due to the difference in how relative paths work when used in CSS files (relative to CSS URL) and when used in HTML files (relative to HTML URL). 这是由于在CSS文件中使用相对路径(相对于CSS URL)和HTML文件中使用相对路径(相对于HTML URL)的方式不同。 To fix this you need to change the path to include the folders that lead to your /images folder. 要解决此问题,您需要更改路径以包括指向/ images文件夹的文件夹。

Code below includes both fixes 下面的代码包含两个修复程序

jQuery(document).ready(function() {
    var images = ['01.jpg', '02.jpg'];
    jQuery('.jumbotron').css({'background-image': 'url(/wp-content/themes/flathost/assets/images/jumbotron/' + images[Math.floor(Math.random() * images.length)] + ')'});
});

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

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