javascript - 单击按钮更改为随机背景图像和相应的文本?

标签 javascript jquery html css

<分区>

假设我有一定数量的图像,我想在我的网站上将其完全覆盖作为背景。

对于每个背景图像,我希望在屏幕中央显示一个特定的文本。

每个背景图像及其对应的文本都应通过单击按钮随机化。

我现在没有任何 JavaScript 或 jQuery,这似乎是解决方案。虽然,我还没有为我的问题找到任何好的代码。是否有代码可以满足我的要求?

谢谢!

JSFiddle网站演示。


HTML:

<div id="background">
    <div id="box">
        <div class="title">TITLE OF WEBSITE</div>
        <div class="text">Text corresponding to the specfic background shown.</div>
        <div class="button">
            <button type="button">Randomizing button</button>
        </div>
    </div>
</div>

CSS:

html, body {
    height: 100%;
}
#background {
    height: 100%;
}
#box {
    background: #fff;
    width: 40%;
    min-width: 400px;
    height: 200px;
    margin-left: auto;
    margin-right: auto;
    top: 40%;
    position: relative;
}
.title {
    width: 100%;
    height: 50px;
    float: left;
    background: #e1e1e1;
    text-align: center;
    font-size: 24px;
    line-height:50px;
}
.text {
    background: #c8c8c8;
    width: 100%;
    height: 100px;
    float: left;
    text-align: center;
    font-size: 18px;
    position: relative;
    padding-top: 20px;
}
.button {
    width: 100%;
    height: 50px;
    float: left;
    text-align: center;
    background: #afafaf;
}

最佳答案

DEMO

HTML:

<div id="background">
    <div id="box">
        <div class="title">TITLE OF WEBSITE</div>
        <div class="text" id="text">Text corresponding to the specfic background shown.</div>
        <div class="button">
            <button type="button" id="btn">Randomizing button</button>
        </div>
    </div>
</div>

JavaScript:

var bks=new Array("http://jsfiddle.net/img/logo.png","http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=3c6263c3453b");
/* This Array 'bk' will hold the random images you want to set as background */
var desc=new Array("JSFIDDLE LOGO","SO SPRITE");
/* This array 'desc' will hold the description of respective image  want to display */
var bk=document.getElementById("background");
var div=document.getElementById("text");
var btn=document.getElementById("btn");
var count=0;
function doIT(){
bk.style["background"]="url('"+bks[count]+"') center center";
    div.innerHTML=desc[count];
    count=count?0:1;
    /* To Change the count randomly use :
     count=Math.floor( Math.random() * ( bks.length - 0 ) ) + 0;
      SEE: http://jsfiddle.net/cu7jcz8m/7/
    */
}

btn.addEventListener("click",doIT);

希望对您有所帮助。干杯 :)!

关于javascript - 单击按钮更改为随机背景图像和相应的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25751061/

相关文章:

JavaScript DOM childNodes.length 也返回文本节点的数量

javascript - 传递包含参数的回调函数?

javascript - js中分隔单个var类型变量

html - 设置默认宽度和最小宽度属性

jquery - 使用 jquery 多次追加表

javascript - iOS 未加载悬停目标点击 URL bc?

javascript - 有没有办法通过http直接加载下载图像到内存?

javascript - 我如何优化 qTip?

javascript - 使用本地 HTML 文件获取远程 JSON 数据(使用 JavaScript - jQuery)

html - 滚动时的视差效果问题