我正在使用下面的 js 插件来进行文本滚动: https://github.com/aamirafridi/jQuery.Marquee
基本上我们只是调用下面的文本滚动:
$('.marquee').marquee();
但我也计划将图像放入滚动文本中。就像readme文件中提到的那样,我们需要像下面这样放置$(window).load,以便它可以准确地计算图像宽度:
$(window).load(function() { $('.marquee').marquee(); });
此函数将在网页加载后加载选取框。
但是如果我只在收到命令后加载选取框怎么办?例如:
receivedCom = function(){ $('.marquee').marquee({duration: 8000}); });
我尝试将 $(window).load 放入 receiveCom 函数中。它不会运行。知道怎么做吗?
最佳答案
我对示例进行了更多修改。由于您知道从服务器发送的图像数量,因此您可以将该数字作为 num_images
传递给客户端。客户端将选取框内容转储到带有 marquee
类的 div
中,然后检查预期的图像是否与选取框 div
中找到的数字匹配>。如果没有,加载仍在进行,我们会每半秒检查一次。加载完成后,我们清除 setInterval
调用并告诉选取框开始。
正如我们在聊天中讨论的,setTimeout
在启动选取框代码时非常有效,因为它在单独的事件循环中执行代码,使插件有机会“查看”新加载的动态图像。如果以下方法不适合您,请尝试稍微增加 setTimeout
延迟。
我添加了 working example它不使用socket.io。在此笔中,内容会动态添加到选取框 div
中,一次添加两个图像。在看到其中的八个图像之前,选取框不会初始化。与下面的代码类似,调用 setInterval
来检查预期图像数量是否与 DOM 中的实际图像数量匹配。
HTML
<div class='marquee'></div>
服务器 JS
// Send the HTML along and the known number of images
// inside the string
socket.emit('your_event_name', {
marquee_content : 'html images and text go here',
num_images : 3
});
客户端JS
var socket = io.connect('http://localhost')
images_expected = 0, // 'num_images' from socket.emit data
interval;
function startMarquee() {
$('.marquee').marquee({duration: 8000});
}
function checkImagesLoaded() {
if ($('.marquee img').length === images_expected) {
clearInterval(interval);
setTimeout(startMarquee); // fire in new event loop
}
}
function insertMarqueeContent(content) {
$(".marquee").html(content);
}
function initMarquee() {
interval = window.setInterval(checkImagesLoaded, 500);
}
socket.on('your_event_name', function (data) {
images_expected = data.num_images;
insertMarqueeContent(data.marquee_content);
initMarquee();
});
关于javascript - 如何将图像放入我的滚动文本js中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36686570/