使用 jQuery 在 div 之间切换
我有两个 div 框 promo1
和 promo2
。显示 promo1
,而隐藏 promo2
。每隔 x 秒,我想切换一下框,以便它隐藏 promo1
并淡入 promo2
,反之亦然。
请原谅我的脚本技巧,我还在学习哈哈。 这就是我到目前为止所得到的。
function switch1(){
$("#promo1").hide("fast");
$("#promo2").fadeIn("slow");
}
function switch2(){
$("#promo2").hide("fast");
$("#promo1").fadeIn("slow");
}
$(document).ready(function() {
setInterval( "switch1()", 5000 );
setInterval( "switch2()", 10000 );
});
现在,正如您所看到的,问题是 switch2
与 switch1
重叠。有没有更简单的方法来实现我在这里想要实现的目标?
I have two div boxes promo1
and promo2
. promo1
is displayed whereas promo2
is hidden. Every x seconds I would like to switch the boxes so it hides promo1
and fades in promo2
and vice versa.
Parden my scripting skills, I'm still learning lol.
This is what I got so far..
function switch1(){
$("#promo1").hide("fast");
$("#promo2").fadeIn("slow");
}
function switch2(){
$("#promo2").hide("fast");
$("#promo1").fadeIn("slow");
}
$(document).ready(function() {
setInterval( "switch1()", 5000 );
setInterval( "switch2()", 10000 );
});
Now the problem with this as you can see is the switch2
overlaps with switch1
. Is there a simpler way to do what I'm trying to achieve here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需使用
.toggle();
http://jsfiddle.net/niklasvh/X6G9Y/
Just use
.toggle();
http://jsfiddle.net/niklasvh/X6G9Y/
您可以使用变量在状态之间切换:
我删除了
hide
上的“fast”参数,因为否则这两个元素会同时显示,除非它们精确定位(或者您链接了效果) ),太丑了。You can use a variable to switch between states:
I removed the "fast" parameter on
hide
because otherwise the 2 elements are displayed at the same time and unless they're positioned precisely (or you chain the effects), it's ugly.不要重新发明轮子
除非您想自学 jQuery,否则最好的解决方案是使用更确定的东西,例如 jQuery 的 Cycle 插件: http://jquery.malsup.com/cycle/
除非您真的想要。 ..
如果您想推出自定义解决方案,以下内容可能会有所帮助。另请注意,与提供的其他一些答案不同,以下内容适用于任意数量的促销 div。当然,您只提到了两个,但您不应该把自己逼到角落:
在线演示: http://jsbin.com /ewusu5/edit
请务必在文档末尾执行此逻辑,或者在如下所示的现成安全方法中执行此逻辑:
Don't Re-Invent the Wheel
Unless you're trying to teach yourself jQuery, the best solution would be to go with something more sure, like the Cycle plugin for jQuery: http://jquery.malsup.com/cycle/
Unless you really want to...
If you'd like to roll a custom solution, the following may help. Note also that the following will work with any number of promo divs, unlike some of the other answers provided. Granted, you only mentioned two but you shouldn't paint yourself into a corner:
Demo online: http://jsbin.com/ewusu5/edit
Be sure to either perform this logic at the end of your document, or within a ready-safe method like the following:
我扩展了已经显示的内容,并添加了一个可以在任何地方使用和放置的指示器功能。 http://jsfiddle.net/BadBoyBill/8yHmy/
I expanded what was already shown and added a indicator feature that can be used and placed anywhere. http://jsfiddle.net/BadBoyBill/8yHmy/