【问题标题】:How to make images change automatically如何使图像自动更改
【发布时间】:2013-12-27 17:35:18
【问题描述】:

我是 javascript 新手,我正在尝试制作一个特色内容滑块,类似于本网站的顶部横幅 http://www.homeplus.co.kr

如您所见,顶部的大横幅会自动更改,并且当用户将鼠标悬停在右侧列表之一上时也会更改。

现在我可以做悬停部分,但我仍然卡在自动更改内容部分。

这是一个示例 jsfiddle:http://jsfiddle.net/StormSdq/5tWPy/2/

<div class="pi">a</div>
<div class="pi">b</div>
<div class="pi">c</div>
<div class="pi">d</div>
<div class="c1">I DREAM</div>
<div class="c1">OF LLAMAS</div>
<div class="c1">JUMPING AROUND</div>
<div class="c1">EATING BUSHES</div>

css:

.pi {
    font-size:12px;
    color:#000;
    font-weight:700;
    width:30px;
    height:25px;
    margin-right:10px;
    background:transparent;
    border-bottom:solid 1px black;
}
.c1 {
    border:1px solid blue;
    background:lightskyblue;
    width:200px;
    height:200px;
    float:right;
    margin-right:430px;
    margin-top:-100px;
    color:red;
    font-size:25px;
    text-align:center;
    display:none;
}

javascript:

div = document.getElementsByClassName('c1');
div[0].style.display = 'block'
B = document.getElementsByClassName('pi');
B[0].onmouseover = function () {
    blip(0);
};
B[1].onmouseover = function () {
    blip(1);
};
B[2].onmouseover = function () {
    blip(2);
};
B[3].onmouseover = function () {
    blip(3);
};

function blip(y) {
    div = document.getElementsByClassName('c1');
    for (x = 0; x < (div.length); x++) {
        div[x].style.display = 'none';
    }
    div[y].style.display = 'block';
}

任何帮助将不胜感激

【问题讨论】:

  • 您已经用 jQuery 标记了它,但在您的 JSFiddle 示例中似乎根本没有使用它。您确定要寻找 jQuery 答案吗?
  • 对不起,我认为 jquery 和 javascript 是一样的,哈哈。对不起这个错误。但是仅使用javascript就可以做到吗?
  • 不用担心。 :) jQuery 是一个流行的 JavaScript 库,可在 jquery.com 获得。
  • 应该这样问问题!
  • 欢迎来到 Stack Overflow。这是一个已经有很多答案的常见问题。建议在询问之前搜索。例如,How to create image slideshow in html?

标签: javascript


【解决方案1】:

试试这个:

var cur = 0; // current index
setInterval(autoAnim, 2000); // auto change every 2s

function autoAnim(){
    if(cur > 3) cur = 0;
    blip(cur);
    cur++;
}

这里是jsfiddle

【讨论】:

  • 哇!谢谢 !这就像魔术一样!哈哈,非常感谢!
【解决方案2】:

您可以使用函数 setTimeout 在 XX 毫秒后调用某些内容。

var number=0;
setTimeout(automatic,5000);  // every 5 seconds

function automatic(){
  blip(number);
  number++;
  if (number > 4)
    number=0;
  alert("Hello");
  setTimeout(automatic,5000);
}

当鼠标悬停和其他一些条件时,您可能希望使函数休眠

【讨论】:

  • 你的意思是setInterval? setTimeout 只执行一次,setInterval 继续每 N 毫秒执行一次..
  • 不,我的意思是 setTimeout 。请参阅运行另一个 setTimeout 的自动功能的末尾。但是 setInterval 可能是一个更好的选择(由 hicurin 回答)
  • 对不起,我并不是说你的答案不正确,它当然会起作用,我只是想指出避免不必要的递归可能是一件好事。
  • 嘿!谢谢你提出你的答案是的!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多