一段时间后在两个jQuery函数之间切换

时间:2019-12-23 15:49:25

标签: jquery html css

我想每5秒在这两个功能之间切换一次。该函数在:after元素中更改网站的背景图像。 我想我必须这样做,因为没有其他方法可以使用jQuery访问:after元素。因此它应该像幻灯片一样工作。

我该如何实现?

function one(){  
var value = "url('/img/img1.png')"
$( "<style>#showcase:after { background-image: " + value + "; }</style>" ).appendTo( "head" )
}

function two(){  
var value = "url('/img/img2.jpg')"
$( "<style>#showcase:after { background-image: " + value + "; }</style>" ).appendTo( "head" )
}

3 个答案:

答案 0 :(得分:4)

对于这种任务,实际上并不需要Javascript / jQuery:您可以使用CSS动画。例如:

#showcase::after {
   content: "";
   background-size: cover;
   display: block;
   width: 100%;
   height: 100vh;
   animation: switchbg 10s linear 0s infinite;
}

@keyframes switchbg {
  0%, 49.99% { background-image: url(https://placekitten.com/2000/1000) }
  50%, 100% { background-image: url(https://placekitten.com/1000/500) }
}
<div id="showcase"></div>

答案 1 :(得分:1)

在样式块之后将样式追加到文档的开头不是好习惯。

一种更好的方法是在元素#showcase上切换一个类。

jQuery附带了一个已被调用的函数:toggleClass

https://api.jquery.com/toggleclass/

因此您可以执行以下操作:

setInterval(() => {
    $('#showcase').toggle('background2');
}, 5000);

然后,您可以简单地控制带有和不带有#showcase类的background2的背景。

答案 2 :(得分:1)

如果您构建一个包含函数的数组,则可以使用setInterval

遍历该数组并围绕该数组

如果要添加更多功能,可以将它们添加到bgImageFunctions数组中

function one () {
  let value = "url('/img/img1.png')"
  console.log("<style>#showcase:after { background-image: " + value + "; }</style>")
  // $("<style>#showcase:after { background-image: " + value + "; }</style>").appendTo("head")
}

function two () {
  let value = "url('/img/img2.jpg')"
  console.log("<style>#showcase:after { background-image: " + value + "; }</style>")
  // $("<style>#showcase:after { background-image: " + value + "; }</style>").appendTo("head")
}

var bgImageFunctions = [ one, two ];
var bgImageIndex = 0;

window.setInterval(function(){
  bgImageFunctions[bgImageIndex++ % bgImageFunctions.length]();
}, 5000);

您还可以通过传递新的URL作为参数来使用一个功能来完成此操作

function updateBackground (value) {
  console.log("<style>#showcase:after { background-image: " + value + "; }</style>")
  // $("<style>#showcase:after { background-image: " + value + "; }</style>").appendTo("head")
}

var bgImageLinks = [ "url('/img/img1.png')", "url('/img/img2.jpg')" ];
var bgImageIndex = 0;

window.setInterval(function(){
  updateBackground(bgImageLinks[bgImageIndex++ % bgImageLinks.length]);
}, 5000);