我正在尝试显示来自数据库的图像,每个图像之间有一个时间延迟。时间延迟可从用户界面选择,并以秒为单位存储在与图像相同的记录中。我已经有了图像显示,但我需要消除动态时间延迟。
时间延迟存储在名为"TimeLapse“的字段中。下面,我尝试在每次while循环显示新图像时将"TimeLapse“的内容用作$HoldTime。
图一的TimeLapse为"5000“。图二的TimeLapse为"15000“。
但它看起来只对两张图片使用了第一个5000的TimeLapse。
有没有人知道我是怎么做到的。
PHP代码
while($row_fb = mysqli_fetch_array($fb)){ ?>
<?php $url = $ImagePath.''.$row_fb['SignageImageName'];
$HoldTime = $row_fb['TimeLapse']?>
<div class="outer">
<div class="banner-container">
<div id="wrapper">
<a><img src="/<?php echo $url;?>" class="responsive"/></a>
</div>
</div>
</div>
<?php
}JAVASCRIPT
(function() {
var a = $('.outer').children();
var index = 0;
run()
function run() {
a.filter('.active').fadeOut(500).removeClass('active');
a.eq(index).fadeIn(500).addClass('active');
index = (index + 1) % a.length;
setTimeout(run, <?php echo $HoldTime;?>);
}
})();发布于 2021-05-31 02:20:14
我会将延迟时间放入HTML data- attribute中,并在JavaScript中读取它来设置延迟。(请注意使用alternative syntax和short echo tags,这会使您的PHP代码在与HTML混合使用时更具可读性。)
<?php while($row = $fb->fetch_array()): ?>
<div class="outer">
<div class="banner-container" data-delay-time="<?=$row['TimeLapse']?>">
<div id="wrapper">
<a>
<img src="/<?=$ImagePath . $row['SignageImageName']?>" class="responsive"/>
</a>
</div>
</div>
</div>
<?php endwhile ?>JS已被清理,以消除对函数外部变量的任何依赖。相反,它只查找活动横幅的下一个同级,如果没有,则循环到开头。对于一个可运行的示例,包含了一些测试HTML。
(function() {
$("div.outer div.banner-container").hide();
run();
function run() {
// get a list of all the banners
var banners = $("div.outer div.banner-container");
if (!banners.length) {
return;
}
// active is the one with "active" class, or the first one
var active = banners.filter(".active").first();
if (!active.length) {
active = banners.first();
}
// get the next one or loop to the beginning again
var next = active.next("div.banner-container");
if (!next.length) {
next = banners.first();
}
active.fadeOut(500).removeClass("active");
next.fadeIn(500).addClass("active");
// get the delay time from the data-delay-time attribute
setTimeout(run, next.data("delayTime"));
}
})();.active {
background: blue;
color: white
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="outer">
<div class="banner-container" data-delay-time="1000">foo</div>
<div class="banner-container" data-delay-time="2000">bar</div>
<div class="banner-container" data-delay-time="6000">baz</div>
<div class="banner-container" data-delay-time="10000">boo</div>
</div>
https://stackoverflow.com/questions/67763417
复制相似问题